我有一个类似于以下的模式:
class Foobar(object): # instances of this class will be referenced by others
def __init__(self, value):
self.value = value
class Foo(object):
def __init__(self, value, foobar)
self.value = value
if isinstance(foobar, Foobar):
self.foobar = foobar
else:
self.foobar = Foobar(foobar)
class Bar(object):
def __init__(self, value, foobar)
self.value = value
if isinstance(foobar, Foobar):
self.foobar = foobar
else:
self.foobar = Foobar(foobar)
这允许 Foo
和 Bar
获取新值(创建 Foobar
)或 Foobar 的现有实例
作为他们的 foobar
参数。
我想去掉这些冗余代码:
# ...
if isinstance(foobar, Foobar):
self.foobar = foobar
else:
self.foobar = Foobar(foobar)
我考虑了以下内容,但由于 Foobar.__new__()
中的无限递归,它不起作用:
class Foobar(object):
def __new__(cls, value):
if isinstance(value, cls):
return value
else:
return Foobar(value)
def __init__(self, value):
self.value = value
class Foo(object):
def __init__(self, value, foobar)
self.value = value
self.foobar = Foobar(foobar)
class Bar(object):
def __init__(self, value, foobar)
self.value = value
self.foobar = Foobar(foobar)
允许类根据传递给 __init__
的值创建新实例或使用现有实例的最佳方法是什么?
最佳答案
您可以通过调用基类 __new__()
来摆脱递归:
class Foobar(object):
def __new__(cls, value):
if isinstance(value, cls):
return value
else:
return object.__new__(cls, value)
def __init__(self, value):
self.value = value
请注意,__new__()
的第一个参数是一个类,而不是self
。
也就是说,我不认为这是一个有用的模式。通常,我建议在构造函数中接受实例并将对象构造留给调用代码。虽然做正确事情的魔法通常看起来很方便,但它通常会导致比其值(value)更多的问题。
关于python - 如何让 __init__ 获取新值或现有实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17348649/