Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: __str__, but for a class, not an instance?

I understand the following Python code:

>>> class A(object):
...     def __str__(self):
...         return "An instance of the class A"
... 
>>> 
>>> a = A()
>>> print a
An instance of the class A

Now, I would like to change the output of

>>> print A
<class '__main__.A'>

Which function do I need to overload to be able to do that? The solution has to work even if the class is never instantiated. Is the situation different in Python 2.x and 3?

like image 262
user1199915 Avatar asked Feb 09 '12 15:02

user1199915


People also ask

What is the use of __ str __ in Python?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.

Is str a class in Python?

Python has a built-in string class named "str" with many handy features (there is an older module named "string" which you should not use). String literals can be enclosed by either double or single quotes, although single quotes are more commonly used.

Can we call class method without creating instance Python?

We can also make class methods that can be called without having an instance. The method is then similar to a plain Python function, except that it is contained inside a class and the method name must be prefixed by the classname. Such methods are known as static methods.

What is Python __ repr __?

In Python, __repr__ is a special method used to represent a class's objects as a string. __repr__ is called by the repr() built-in function. You can define your own string representation of your class objects using the __repr__ method. Special methods are a set of predefined methods used to enrich your classes.


2 Answers

Define __str__() on the metaclass:

class A(object):
    class __metaclass__(type):
        def __str__(self):
            return "plonk"

Now, print A will print plonk.

Edit: As noted by jsbueno in the comments, in Python 3.x you would need to do the following:

class Meta(type):
    def __str__(self):
        return "plonk"
class A(metaclass=Meta):
    pass

Even in Python 2.x it might be a better idea to define the metaclass outside the class body -- I chose the nested form above to save some typing.

like image 182
Sven Marnach Avatar answered Sep 18 '22 22:09

Sven Marnach


Define the __repr__ method on your meta class:

class MetaClass(type):

    def __repr__(self):
          return "Customized string"

class TestClass(object):
   __metaclass__  = MetaClass


print TestClass # Customized string
like image 30
Mariusz Jamro Avatar answered Sep 19 '22 22:09

Mariusz Jamro