从子类实例访问父类实例属性?

时间:2012-06-06 06:15:26

标签: python class instance parent

如何在此代码示例中从“child”访问“myvar”:

class Parent():
    def __init__(self):
        self.myvar = 1

class Child(Parent):
    def __init__(self):
        Parent.__init__(self)

        # this won't work
        Parent.myvar

child = Child()

4 个答案:

答案 0 :(得分:9)

父类是一个类 - 蓝色打印不是它的实例, 在OOPS中访问对象的属性它需要相同的实例, 这里的自/子是实例,而父/子是类......

请参阅下面的答案,可能会澄清您的疑虑。

class Parent():
    def __init__(self):
        self.myvar = 1

class Child(Parent):
    def __init__(self):
        Parent.__init__(self)

        # here you can access myvar like below.
        print self.myvar

child = Child()
print child.myvar

答案 1 :(得分:7)

Parent没有名为myvar的属性。只有父级的实例具有该属性。在Child的方法中,您可以使用self.myvar访问该属性。

答案 2 :(得分:0)

您首先需要使用命令“ super”通过所谓的代理对象来初始化父类。

所以代码将像这样:

class Parent():
  def __init__(self):
      self.myvar = 1

class Child(Parent):
  def __init__(self):
      super.__init__()


child = Child()
print child.myvar

答案 3 :(得分:0)

使用继承的替代方法

当前的答案来自继承的角度,但这并不总是您想要的——有时您可能希望孩子成为与父母完全不同类型的对象,但是仍然可以访问父属性。

对于业务模拟,请考虑 Excel 工作簿,其中包含工作表子项,其本身具有范围子项等。

独生子女

另一种方法(并非唯一方法)是将父项作为参数传递给子项以创建与父项对应的属性:

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)        # prints 1

new_child = new_parent.child
print(new_child.child_value)          # prints 0
print(new_child.parent.parent_value)  # prints 1

new_parent.parent_value = 100
print(new_child.parent.parent_value)  # prints 100

请注意,这会在实例化 child 的同时实例化 new_parent。要访问父级的属性,只需通过 parent 属性。

多个孩子

您可以扩展它,以便您可以通过 Child 对象创建 new_parent 类的多个实例。下面的代码是执行此操作的一种简单方法,它将 child 属性替换为 children 属性和 add_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  # allows add_child to assign a variable


class Child(object):
    def __init__(self, child_value, _parent):
        self.parent = _parent
        self.child_value = child_value


new_parent = Parent(1)

# add 3 Child instances with child_values 2, 4, 8
[new_parent.add_child(v) for v in [2, 4, 8]]

# add another child that utilises the return statement
extra_child = new_parent.add_child(16)

for child in new_parent.children:
    print(child.child_value)          # prints 2, 4, 8, 16
    print(child.parent.parent_value)  # prints 1

new_parent.parent_value = 32
for child in new_parent.children:
    print(child.parent.parent_value)  # prints 32

# prove that extra_child is new_parent.children[3]
extra_child.child_value = 64
print(new_parent.children[3].child_value)  # prints 64