3

So the situation I want to resolve is pretty simple. Say I have a subclass C that extends parents B and A. Parents B, and A each have their own __repr__ methods. When I print C, the __repr__ method of parent A is always invoked, but I want to invoke parent B's.

How can I do this?

Maroun
  • 91,013
  • 29
  • 181
  • 233
user1925767
  • 83
  • 1
  • 5
  • possible duplicate of [Python's Multiple Inheritance: Picking which super() to call](http://stackoverflow.com/questions/14206015/pythons-multiple-inheritance-picking-which-super-to-call) – Jeff Mercado Jul 27 '14 at 06:58

2 Answers2

4

Assume A is defined like this:

class A():
    def __repr__(self):
        return "This is A"

and B is defined similarly:

class B():
    def __repr__(self):
        return "This is B"

while C is defined like so:

class C(A, B):
    def __init__(self):
        pass

or something similar. print A() will yield This is A, while the same for B will yield This is B. print C() will, as you describe, give This is A. However, if you just change the order of C's inheritance:

class C(B, A): # change order of A and B
    def __init__(self):
        pass

then print C() will give you This is B. Simple as that.

MattDMo
  • 96,286
  • 20
  • 232
  • 224
1

If all I wanted was to call an inherited class's repr I would just do:

class C(B, A): # whatever order
    def __repr__(self):
        return A.__repr__(self)

I had a case similar, but slightly different to this question. I wanted to print the default repr of an inherited class. For me class C was dynamically defined with B being a mixin class, but I wanted to show the name and module of the "main" class A. I ended up with this solution.

class C(B, A):
    def __repr__(self):
        '''Override repr to show the name and path of the main cls.'''
        return '<{} {}.{} object at {}>'.format(
            self.__class__.__name__,
            A.__module__,
            A.__name__,
            hex(id(self)))
Al Conrad
  • 1,320
  • 15
  • 11