【发布时间】:2013-09-14 11:18:51
【问题描述】:
我想知道从嵌套子类访问父变量的最佳方式是什么,目前我正在使用装饰器。
这是唯一/最好的方法吗???
我不想直接访问父变量(例如 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()
这显然是一个简单的例子,它遗漏了所有真正的逻辑,因此许多类看起来是无效的,但实际上是必要的。
【问题讨论】:
标签: python oop inheritance nested