替代继承的方法
目前的答案都是从 继承 的角度来看的,但这并不总是你想要的方式 -- 有时你可能希望子类是与父类完全不同的对象类型,但仍可以访问父类的属性。
以业务为例,可以想象 Excel 中的工作簿(Workbook)有工作表(Worksheet)子项,它们又有范围(Range)等子项。
只有子项
另一种方法(不是唯一的方法)是将父类作为参数传递给子类,以创建对应于父类的属性:
class Parent(object):
def __init__(self, parent_value):
self.parent_value = parent_value
self.child = Child(self)
class Child(object):
def __init__(self, _parent):
self.parent = _parent
self.child_value = 0
new_parent = Parent(1)
print(new_parent.parent_value)
new_child = new_parent.child
print(new_child.child_value)
print(new_child.parent.parent_value)
new_parent.parent_value = 100
print(new_child.parent.parent_value)
注意,这会同时实例化child
和new_parent
。要访问父类的属性,请通过parent
属性进行访问。
多个子类
您可以扩展这个功能,以便通过new_parent
对象创建Child
类的多个实例。以下代码是一种简单的方法,它用一个children
属性和一个add_child
方法替换了child
属性。
class Parent(object):
def __init__(self, parent_value):
self.parent_value = parent_value
self.children = []
def add_child(self, child_value):
new_child = Child(child_value, _parent=self)
self.children.append(new_child)
return new_child
class Child(object):
def __init__(self, child_value, _parent):
self.parent = _parent
self.child_value = child_value
new_parent = Parent(1)
[new_parent.add_child(v) for v in [2, 4, 8]]
extra_child = new_parent.add_child(16)
for child in new_parent.children:
print(child.child_value)
print(child.parent.parent_value)
new_parent.parent_value = 32
for child in new_parent.children:
print(child.parent.parent_value)
extra_child.child_value = 64
print(new_parent.children[3].child_value)
self.__myvar
)开头,它将不起作用,因为Python认为它是私有的。 - ihadanny