Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify the string representation for a class

Tags:

python

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.

like image 808
RussAbbott Avatar asked Nov 30 '25 02:11

RussAbbott


1 Answers

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
like image 75
blhsing Avatar answered Dec 02 '25 16:12

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!