RussAbbott
RussAbbott

Reputation: 2738

How to specify the string representation for a class

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.

Upvotes: 3

Views: 64

Answers (1)

blhsing
blhsing

Reputation: 107115

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

Upvotes: 4

Related Questions