所以我创建了两个元组的子类,并希望根据某些条件创建一个或另一个。我知道工厂模式,这将是适当的解决方案,但在我的具体情况下,我不能使用它 - 坦率地说,我想了解:)
更具体地说,我想知道在通过__init__
创建对象后何时调用__new__
以及何时(以及为什么)创建对象。
以下代码示例应说明我尝试实现的目标:
class my_special_interval(tuple):
def __init__(self,a,b):
print("my_special_interval")
self.a = a
self.b = b
def __new__(cls, a, b):
if a > b:
return super(my_special_interval, cls).__new__(my_special_interval, (a, b))
else:
obj = super(my_special_interval, cls).__new__(my_second_special_interval, (a, b))
print("Explicit init necessary:")
obj.__init__(a,b)
return obj
class my_second_special_interval(tuple):
def __init__(self,a,b):
print("my_second_special_interval")
self.a = a
self.b = b
def __new__(cls, a, b):
if a > b:
obj = super(my_second_special_interval, cls).__new__(my_special_interval, (a, b))
print("Explicit init necessary:")
obj.__init__(a,b)
else:
return super(my_second_special_interval, cls).__new__(my_second_special_interval, (a, b))
if __name__ == '__main__':
a = 2.0
b = 1.0
iv1 = my_special_interval(a,b)
a = 1.0
b = 2.0
iv2 = my_special_interval(a,b)
a = 2.0
b = 1.0
iv1 = my_second_special_interval(a,b)
a = 1.0
b = 2.0
iv2 = my_second_special_interval(a,b)
这导致以下打印输出:
my_special_interval
Explicit init necessary:
my_second_special_interval
Explicit init necessary:
my_special_interval
my_second_special_interval
THX,
垫