Access parent class instance attribute from child class instance?

≡放荡痞女 提交于 2019-11-30 23:15:24

问题


How to access "myvar" from "child" in this code example:

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()

回答1:


Parent is a class - blue print not an instance of it, in OOPS to access attributes of an object it requires instance of the same, Here self/child is instance while Parent/Child are classes...

see the answer below, may clarify your doubts.

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



回答2:


Parent does not have an attribute called myvar. Only instances of parent have that attribute. From within a method of Child, you can access that attribute with self.myvar.




回答3:


You need to initiate the parent class first via so-called proxy object using command "super".

So the code will be like this:

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

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


child = Child()
print child.myvar


来源:https://stackoverflow.com/questions/10909032/access-parent-class-instance-attribute-from-child-class-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!