python Python覆盖类(不是实例)特殊方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2497790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
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:
我希望能够__str__()
在不创建实例的情况下调用类的方法。例子:
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__()
.
即使我使用@staticmethod
或@classmethod
将__str__
依然采用内置Python定义__str__
。它仅在它是Foo().__str__()
而不是Foo.__str__()
.
回答by Anurag Uniyal
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)
__str__
类中定义的特殊方法仅适用于该类的实例,要使类对象具有不同的行为,您必须在该类的元类中执行此操作,例如(python 2.5)
class Meta(type):
def __str__(self):
return "Klass"
class A(object):
__metaclass__ = Meta
def __str__(self):
return "instance"
print A
print A()
output:
输出:
Klass
instance
回答by bignose
Why do you want to abuse the meaning of __str__
? That method name (like many dunder method names) is special in Python, being an instance method with the meaning "return a string representation of this instanceof the class".
你为什么要滥用 的意思__str__
?该方法名称(如许多 dunder 方法名称)在 Python 中很特殊,它是一个实例方法,意思是“返回该类实例的字符串表示”。
If you want a function that just returns a static string, it would be better to have that as a separate function not inside a class.
如果你想要一个只返回静态字符串的函数,最好将它作为一个单独的函数而不是在类中。
If you want a constructor that returns a new string, name it something else so it's not clobbering the special __str__
name.
如果您想要一个返回新字符串的构造函数,请将其命名为其他名称,以免破坏特殊__str__
名称。
If you want a method for printing a representation of the class, you should not use the name __str__
for that. That name is – as the dunder-style name implies– expected to have particular behaviour as defined in the Python documentation. Choose some (non-dunder) name which you can give your special meaning, and don't forget to make it a class method.
如果您想要一种打印类表示的方法,则不应__str__
为此使用名称。该名称 - 正如dunder 风格的名称所暗示的- 预计具有Python 文档中定义的特定行为。选择一些(非dunder)名称,您可以赋予其特殊含义,并且不要忘记将其设为类方法。
回答by Charles Merriam
I'm not sure what you are trying to do, exactly. Let me just add a bit of random information.
我不确定你到底想做什么。让我添加一些随机信息。
First, add this class:
首先,添加这个类:
class FooNew(object):
def __str__(self):
return 'Fubar'
Print this instead:
改为打印:
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?")
To get 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?
Are you absolutely sure you don't want to call a classmethod?
您绝对确定不想调用类方法吗?