Python重写类(非实例)特殊方法

Python重写类(非实例)特殊方法,python,class,overriding,Python,Class,Overriding,如何重写类的特殊方法 我希望能够在不创建实例的情况下调用类的\uuu str\uuu()方法。例如: class Foo: def __str__(self): return 'Bar' class StaticFoo: @staticmethod def __str__(): return 'StaticBar' class ClassFoo: @classmethod def __str__(cls):

如何重写类的特殊方法

我希望能够在不创建实例的情况下调用类的
\uuu str\uuu()
方法。例如:

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())
产生:


酒吧
静电棒
分类栏
应该是:

条
酒吧
静电棒
静电棒
分类栏
分类栏

即使我使用了
@staticmethod
@classmethod
\uuuuu str\uuuu
仍在使用内置的Python定义。只有当它是
Foo()。\uuu str\uuu()
而不是
Foo.\uu str\uuu()
时,它才起作用。为什么你想滥用
\uu str\uuu>
的含义?该方法名(like)在Python中是特殊的,是一个实例方法,其含义是“返回类的此实例的字符串表示”

如果您想要一个只返回静态字符串的函数,最好将其作为一个单独的函数,而不是在类中

如果您想要一个返回新字符串的构造函数,请将其命名为其他名称,这样它就不会破坏特殊的
\uuu str\uu
名称


如果需要打印类表示的方法,则不应使用名称
\uuu str\uuu
。这个名字是——正如人们所期待的那样。选择一些你可以赋予你特殊含义的(非dunder)名称,别忘了将其作为类方法。

类中定义的特殊方法
\uuuu str\uuu
仅适用于该类的实例,要使类对象具有不同的行为,你必须在该类的元类中执行,例如(python 2.5)

输出:

Klass
instance

我不确定你到底想做什么。让我添加一点随机信息

首先,添加此类:

class FooNew(object):
def __str__(self):
    return 'Fubar'
改为打印以下内容:

if __name__ == '__main__':
    print "You are calling type for an old style class"
    print(Foo)
    print(type.__str__(Foo))
    print(Foo())
    print("But my Python 2.6 didn't match your output for print(Foo)")
    print("You are calling object.str() for a new style class")
    print(FooNew)
    print(object.__str__(FooNew))
    print(FooNew())
    print("Why do you want to change this?")
要获得此信息:

You are calling type for an old style class
__main__.Foo
<class __main__.Foo at 0xb73c9f5c>
Bar
But my Python 2.6 didn't match your output for print(Foo)
You are calling object.str() for a new style class
<class '__main__.FooNew'>
<class '__main__.FooNew'>
Fubar
Why do you want to change this?
您正在为旧式类调用type
__美赞臣
酒吧
但是我的Python 2.6与您的打印输出(Foo)不匹配
您正在为新样式类调用object.str()
伏巴舞
你为什么要改变这个?

你确定不想调用classmethod吗?

我不得不使用C类(metaclass=M)的新py3语法:。。。但它是有效的-1:“在不创建实例的情况下调用类的
\uuu str\uu()
方法”。打破了任何人对物体的理解。请不要这样做。这使得该计划完全违背了我们最基本的期望。我不同意。如果您调用str(MyClass),那么就没有理由期望它的行为就像您刚才调用str(myClassObject)一样。也就是说,一开始就没有基本的期望。我怀疑他想创建一个静态类,但从来没有打算创建它的任何实例。”该方法保留了“返回此实例的字符串表示形式”的含义@timgeb:我已经更新了答案,谢谢。
You are calling type for an old style class
__main__.Foo
<class __main__.Foo at 0xb73c9f5c>
Bar
But my Python 2.6 didn't match your output for print(Foo)
You are calling object.str() for a new style class
<class '__main__.FooNew'>
<class '__main__.FooNew'>
Fubar
Why do you want to change this?