简体   繁体   中英

Python Parent Class Instance Variables

I have a parent class named parent and its like this:

class parent(object):

    def __init__(self,p1,p2):
        super(parent,self).__init__()
        self.p1= p1
        self.p2= p2

I have another child class that looks like the following:

class child(parent):

    def __init__(self,p1,p2,p3):
        super(child,self).__init__()
        self.p1 = p1
        self.p2 = p2
        self.p3 = p3

This child class has one extra instance variable called p3 . What I am trying to do is have the ability to create objects with parameters. These parameters are used to update both the inherited variables p1 & p2 of class parent and its own instance variables p3 . But when I run the above, I get error:

if __name__ == "__main__":
    p1 = parent('p1_parent','p2_parent')


    p2 = child('p1_child','p1_child','p1_child')

error:

TypeError: __init__() takes exactly 3 arguments (1 given)

You need to pass p1 and p2 to the parent class constructor:

super(child, self).__init__(p1, p2)

Example:

class parent(object):
    def __init__(self,p1,p2):
        super(parent, self).__init__()
        self.p1= p1
        self.p2= p2

class child(parent):
    def __init__(self,p1,p2,p3):
        super(child,self).__init__(p1, p2)
        self.p3 = p3


child1 = child(1,2,3)
print child1.p1, child1.p2, child1.p3

prints: 1 2 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM