1

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)
1
  • Why are you calling super(Event, self) when the class isn't Event? Event doesn't even appear in the inheritance hierarchy. Commented Mar 19, 2014 at 2:47

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

if so do I still need to the lines self.p1 = p1 and self.p2 = p2 or with your answer it will automatically fill those values in?
@user1234440 nope, you don't need self.p1 = p1 and self.p2 = p2.
@alecxe How many instance variables does the child class have? 1 (p3) or 3 (p1,p2,p3)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.