我有一个类,它应该包含几个其他类作为它的属性 - 我相信组合是合适的术语。现在,我想初始化包含的类的属性,具体取决于它们是否已在包含类中设置。在下面的例子中,我也只是覆盖两个小类别的默认值与None
,我不想:在另一个类中初始化一个类,但只传递设置属性
class OneAttribute:
def __init__(self,a=1):
self.a = a
class TwoAttributes:
def __init__(self,b=2,c=3):
self.b = b
self.c = 3
class SuperClass:
def __init__(self,a=None,b=None,c=None):
'''
This would override the defaults in the
other two classes, which is bad.
'''
self.one = OneAttribute(a=a)
self.two = TwoAttributes(b=b,c=c)
我也可以这样定义下面包含类,但这不是很好,也不扩展只是可怕:
Class SuperClass:
def __init__(self,a=None,b=None,c=None):
if a is not None:
self.one = OneAttribute(a=a)
else:
self.one = OneAttribute()
if b is not None and c is not None:
self.two = TwoAttributes(b=b, c=c)
elif b is not None:
self.two = TwoAttributes(b=b)
elif c is not None:
self.two = TwoAttributes(c=c)
else:
self.two = TwoAttributes()
是什么,我想,也许实现了糟糕的设计决策?
为什么是de 'SuperClass'中的错误值与其他类中的错误值不同?你可以让他们一样吗? – BrenBarn
是'def __init __(self,a = 1,b = 2,c = 3):'一个选项?然后你可以分别调用'OneAttribute(a)'和'TwoAttributes(b,c)'。 – Hyperboreus
你没有提到的一件事是你可以将所有'if _不是None'条件移入子类'__init__'方法中。通过这种方式,您可以像第一个示例一样保留'SuperClass'定义,并且只传入子类可以处理的'None'或子类应该设置的值。 –