0

How do I use multiple __str__ from other classes? For example:

class A:
    def __str__(self):
        return "this"

class B:
    def __str__(self):
        return "that"

class C(A,B):
    def __str__(self):
        return super(C, self).__str__() + " those"
        # return something(A) + " " something(B) + " those"

cc = C()
print(cc)

Output: this those

I would like the output to be: this that those

This post is almost a solution (with super())

famaral42
  • 695
  • 7
  • 9

3 Answers3

7

With multiple inheritance, super() searches for the first class that has the attribute, as they appear, from left to right. So, it will stop at A. You can access all the parent classes with the special __bases__ attribute, and loop over them, calling str on each one.

blue_note
  • 27,712
  • 9
  • 72
  • 90
2

Call parent classes __str__ methods explicitly:

class C(A, B):
    def __str__(self):
        return A.__str__(self) + ' ' + B.__str__(self) + ' those'
        # or return '{} {} those'.format(A.__str__(self), B.__str__(self))
ingvar
  • 4,169
  • 4
  • 16
  • 29
1

I tried adding this code example to the blue_note answer but he reverted the change so reposting as an answer.

Direct super() invocations don't quite work here with multiple inheritance. It'll stop at the first found __str__ method. Instead you can call all the parent __str__ methods by iterating over __bases__. Keep in mind, this will return the object type as well. Which may or may not be desired.

Example:

def __str__(self) -> str:
    bstr = ""
    for base in type(self).__bases__:
        bstr += base.__str__(self) if base.__name__ != 'object' else ""
    return bstr
Ifrit
  • 6,791
  • 8
  • 50
  • 79