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?
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.
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.
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.
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.
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.
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
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