How do I override a class special method?
I want to be able to call the __str__() method of the class without creating an instance. Example:
class Foo:
def __str__(self):
return 'Bar'
class StaticFoo:
@staticmethod
def __str__():
return 'StaticBar'
class ClassFoo:
@classmethod
def __str__(cls):
return 'ClassBar'
if __name__ == '__main__':
print(Foo)
print(Foo())
print(StaticFoo)
print(StaticFoo())
print(ClassFoo)
print(ClassFoo())
produces:
<class '__main__.Foo'>
Bar
<class '__main__.StaticFoo'>
StaticBar
<class '__main__.ClassFoo'>
ClassBar
should be:
Bar
Bar
StaticBar
StaticBar
ClassBar
ClassBar
Even if I use the @staticmethod or @classmethod the __str__ is still using the built-in Python definition for __str__. It’s only working when it’s Foo().__str__() instead of Foo.__str__().
Special method
__str__defined in a class works only for the instances of that class, to have the different behavior for class objects you will have to do it in a metaclass of that class e.g. (python 2.5)output: