Carlos
Carlos

Reputation: 125

Calling object method inheriting from two classes

I have three classes A, B and C.

A has a method hello(self). B inherits from A and implements a new method hello(self). C inherits from B and reimplements the method hello(self).

Now if I create an instance b = B() and call b.hello() it calls as it should B.hello(b).

The problem is that when I create an object c = C() and call c.hello() it calls actually B.hello(c) instead of C.hello(c). Why is that?

My code looks like this:

class A:
    def hello(self):
        self.helloHandler()
    def helloHandler(self):
        print('class A method')

class B(A):
    def helloHandler(self):
        print('class B method')

class C(B):
    def helloHandler(self):
        print('class C method')

c = C()
c.hello()

This works but not mine. My code has several thousand lines at this point... Can't really post it but that is the point. I don't know what can be the problem. I use abcmeta if that matters for some obscure reason to force the child class to have some methods implemented.

Edit: I messed up two of my objects that look the same. Everything works as it should!

Upvotes: 0

Views: 39

Answers (2)

Carlos
Carlos

Reputation: 125

I got confused between all my classes. I have two objects that look very similar... everything works as it should.

Upvotes: 0

James
James

Reputation: 36608

I cannot reproduce your problem. Here is the setup as you have defined it, B inherits from A but overloads its method; C inherits from B but again overloads its method.

Creating an instance of C and calling hello() uses the correct overloaded method from C.

class A:
    def hello(self):
        print('class A method')

class B(A):
    def hello(self):
        print('class B method')

class C(B):
    def hello(self):
        print('class C method')

c = C()
c.hello()
# prints
class C method

Upvotes: 2

Related Questions