我想知道从嵌套子类访问父变量的最佳方法是什么,目前我正在使用装饰器。
这是唯一/最好的方法???
我不想直接访问父变量(例如 ComponentModel.origin (见下文)),因为这需要“配置”文件中的更多代码,所以我想知道是否可以在有问题的子类继承自哪个类?
我当前解决方案的简单示例:
# defined in a big library somewhere:
class LibrarySerialiser(object):
pass
# defined in my module:
class ModelBase:
pass
class SerialiserBase(LibrarySerialiser):
def __init__(self, *args, **kwargs):
# could i some how get hold of origin here without the decorator?
print self.origin
super(SerialiserBase, self).__init__(*args, **kwargs)
def setsubclasses(cls):
cls.Serialiser.origin = cls.origin
return cls
# written by "the user" for the particular application as the
# configuration of the module above:
@setsubclasses
class ComponentModel(ModelBase):
origin = 'supermarket'
class Serialiser(SerialiserBase):
pass
ser = ComponentModel.Serialiser()
这显然是一个简单的例子,它错过了所有真正的逻辑,因此许多类看起来是无效的,但确实是必要的。