Access parent class instance attribute from child class instance?

user975135 picture user975135 · Jun 6, 2012 · Viewed 38.7k times · Source

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

Answer

Japan Shah picture Japan Shah · Jun 6, 2012

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