我想构建一个类,该类具有一个类方法,该类返回一个实例化的类的实例,该实例使用从私有类属性中提取的任何预定义的默认值集。但是,我发现,如果我创建一个带有私有类属性覆盖的子类,则类方法似乎仍然使用父类的版本!为什么会这样?
这是一个MWE,展示了这个问题:
class MyCoolBeansClass:
__MyCoolBeansPrivateAttr = {'FizzBuzz': {'foo': 'Fizz', 'bar': 'Buzz'},
'WimWam': {'foo': 'Wim', 'bar': 'Wam'}}
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
def __str__(self):
return 'foo: {foo}\tbar: {bar}'.format(foo=self.foo, bar=self.bar)
@classmethod
def specificBeanz(cls, cbtype, printclass=False):
""" Create a specific instance from a pre-determined set of instances """
if printclass:
print("Class Name: " + cls.__name__)
if cbtype not in cls.__MyCoolBeansPrivateAttr.keys():
raise ValueError('Invalid pre-determined Beanz, valid values are: ' +
', '.join(cls.__MyCoolBeansPrivateAttr.keys()))
kwargs = cls.__MyCoolBeansPrivateAttr[cbtype]
return cls(**kwargs)
class MyCubeGleamer(MyCoolBeansClass):
__MyCoolBeansPrivateAttr = {'GleamCube': {'foo': 'Gleam', 'bar': 'Cube'},
'FogSnarl': {'foo': 'Fog', 'bar': 'Snarl'}}
if __name__ == "__main__":
FizzBuzz = MyCoolBeansClass.specificBeanz('FizzBuzz', printclass=True)
print(FizzBuzz)
WimWam = MyCoolBeansClass.specificBeanz('WimWam', printclass=True)
print(WimWam)
GleamCube = MyCubeGleamer.specificBeanz('GleamCube', printclass=True)
print(GleamCube)
运行此命令:
> testinheritance.py
Class Name: MyCoolBeansClass
foo: Fizz bar: Buzz
Class Name: MyCoolBeansClass
foo: Wim bar: Wam
Class Name: MyCubeGleamer
-----------------------------------------------------------------------------
Traceback (most recent call last):
File "testinheritance.py", line 37, in <module>
GleamCube = MyCubeGleamer.specificBeanz('GleamCube', printclass=True)
File "testinheritance.py", line 21, in specificBeanz
', '.join(cls.__MyCoolBeansPrivateAttr.keys()))
ValueError: Invalid pre-determined Beanz, valid values are: FizzBuzz, WimWam
-----------------------------------------------------------------------------
正如您所看到的,在MyCubeGleamer.specificBeanz()
来电中,cls.__name__
似乎工作正常,但cls.__MyCoolBeansPrivateAttr
正在检索MyCoolBeansClass.__MyCoolBeansPrivateAttr
。
答案 0 :(得分:3)
正确。双重初始下划线会破坏属性名称,以便阻止子项轻松访问它们。它们不是,但实际上是私有的,因为没有&#34;私有&#34;在Python中。将属性名称切换为使用单个初始下划线。