4

Below is my code:

class Parent1(object):
    def __init__(self):
        print "!!! ___initialization Parent1___ !!!"

    def method(self):
        print "*** method of Parent1 is called ***"


class Parent2(object):
    def __init__(self):
        print "!!! ___initialization Parent2___ !!!"

    def method(self):
        print "*** method of Parent2 is called ***"

class Child(Parent1,Parent2):
    def __init__(self):
        print "!!! ___initialization Child___ !!!"

    def method(self):
        super(Child,self).method()
        print "*** method of Child is called ***"


Ch = Child()
Ch.method()

I want to call method() of Parent2 class using object of child class. Conditions are only child class object should be created and no change in child class declaration (class Child(Parent1,Parent2): should not changed.)

1 Answer 1

4
Parent2.method(self)

That's all you need - the instance.method() is just syntactic sugar for ClassName.method(instance), so all you need to do is call it without the syntactic sugar and it'll do fine.

I changed the Child class to this:

class Child(Parent1,Parent2):
    def __init__(self):
        print "!!! ___initialization Child___ !!!"

    def method(self):
        super(Child,self).method()
        print "*** method of Child is called ***"
        Parent2.method(self)

And:

# Out:
$ python c.py
!!! ___initialization Child___ !!!
*** method of Parent1 is called ***
*** method of Child is called ***
*** method of Parent2 is called ***

You get the expected output perfectly fine.

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

4 Comments

You might as well change super(Child, self).method() to Parent1.method(self) as well. This class hierarchy is not designed to use super properly.
@James: Thanks for the solution. Is this the only way to do it? Is there any other way? Can't it be done using super() or decorator?
@Praveenkumar I'm not aware of one, but I'm by no means an expert on Python inheritance, it's possible there's some way I don't know of.
@James. Yes I will. :)

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.