Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does python variable inheritance work

I'm trying something very basic with Python inheritance:

class Parent:
    def __init__(self):
        self.text = 'parent'

    def getText(self):
        print self.text

class Child1(Parent):
    def __init__(self):
        self.x = 'x'

class Child2(Parent):
    def __init__(self):
        self.x = 'x'

if __name__ == "__main__": 
    parent = Parent()
    child1 = Child1()
    child2 = Child2()

    parent.getText()
    child1.getText()
    child2.getText()

but I keep getting

Child1 instance has no attribute 'text'

how are variables passed to children?

like image 986
duxfox-- Avatar asked Mar 03 '16 15:03

duxfox--


1 Answers

You need to call the constructor of the parent classes manually - Here, self.text is initialize in Parent constructor which is never called:

class Child1(Parent):
    def __init__ (self):
        super(Child1, self).__init__ ()
        # or Parent.__init__ (self)
        self.x = 'x'
like image 159
Holt Avatar answered Sep 20 '22 21:09

Holt