-1

I'm struggling to figure out how to call the base class implementation of stringification in Python. The following illustrates what I am attempting to do:

class A:
    def __init__(self, text):
        self.text = text

    def __str__(self):
        return self.text

class B(A):
    def __init__(self, prefix, suffix):
        A.__init__(self, prefix)
        self.suffix = suffix

    def __str__(self):
        return self.suffix

    def __format__(self, fmt):
        return f'{str(super(A, self))}, {self.suffix}'

foo = B('hello', 'world')
print(f'{foo}')

My expectation was that the above prints "hello, world". It is currently printing "<super: <class 'A'>, <B object>>, world". I have tried everything I can think of to call the base class implementation of the str method, but can't for the life of me figure out the syntax. What is the syntax to call the base class implementation of __str__ from within B.__format__?

4
  • Hello Jeff, to begin with, your code is not correct. The first line of the _init__() method of class *B* should be: super().__init__( prefix ). It is the same but clearer. The real problem lies in the _str__ () method of that class, whose return should be: return super().__str__() + “ ” + self.suffix. Another part of the problem is that print() automatically calls _str_ (), but f does not, so you have to use: print( foo ) or print( f“ {foo.__str__()}” ). Commented yesterday
  • Another question closed as a “duplicate” that is not a duplicate (at least of the answer they link to), and so it goes... Commented yesterday
  • @MarcePuente, this was a contrived example. In the real code, the classes utilize multiple inheritance. So to summarize your comment as I understand it applies to multiple inheritance, you are proposing the solution super(A, self).__str__(). My understanding is this is just an alternate syntax to A.__str__(self), but please correct me if that is wrong. The fact that the example calls the __format__ method was intentional. The B.__str__ method was added to ensure any proposed answer correctly called the base class implementation. Commented 22 hours ago
  • 1
    If there is multiple inheritance, disregard my comment, just keep in mind the modification of _str__() (so that it returns both strings), and that when you use print( myObject ), print() calls the object's method _str__(), but not when you use print(f“”). Commented 17 hours ago

1 Answer 1

-2

Ah, finally figured it out. The answer is to call A.__str__(self). Syntax figured out from this duplicate post: python call method of specified base class

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.