Python overriding class (not instance) special methods
- by André
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__().