Python overriding class (not instance) special methods

Posted by André on Stack Overflow See other posts from Stack Overflow or by André
Published on 2010-03-23T05:35:25Z Indexed on 2010/03/23 5:43 UTC
Read the original article Hit count: 307

Filed under:
|
|

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__().

© Stack Overflow or respective owner

Related posts about python

Related posts about override