Suppose I have:
class A:
@classmethod
def __str__(cls): return 'A'
The intent is for str(A) to return 'A'.
But instead I get <class '__main__.A'>.
The same thing happens when I define __repr__.
How can I define a string representation for a class?
I need something that will respond to str(A) since I don't have control over the call.
You can use a metaclass that overrides the __str__ method of the base class of a class object, type:
class meta(type):
def __str__(cls):
return cls.__name__
class A(metaclass=meta):
pass
print(str(A))
This outputs:
A
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With