use*_*915 8 python string class
我理解以下Python代码:
>>> class A(object):
... def __str__(self):
... return "An instance of the class A"
...
>>>
>>> a = A()
>>> print a
An instance of the class A
Run Code Online (Sandbox Code Playgroud)
现在,我想改变输出
>>> print A
<class '__main__.A'>
Run Code Online (Sandbox Code Playgroud)
我需要哪个函数来重载才能做到这一点?即使从未实例化类,解决方案也必须工作.Python 2.x和3中的情况有所不同吗?
Sve*_*ach 11
__str__()在元类上定义:
class A(object):
class __metaclass__(type):
def __str__(self):
return "plonk"
Run Code Online (Sandbox Code Playgroud)
现在,print A将打印plonk.
编辑:正如jsbueno在评论中所述,在Python 3.x中,您需要执行以下操作:
class Meta(type):
def __str__(self):
return "plonk"
class A(metaclass=Meta):
pass
Run Code Online (Sandbox Code Playgroud)
即使在Python 2.x中,在类体外部定义元类也是一个更好的主意 - 我选择上面的嵌套形式来保存一些输入.
__repr__在元类上定义方法:
class MetaClass(type):
def __repr__(self):
return "Customized string"
class TestClass(object):
__metaclass__ = MetaClass
print TestClass # Customized string
Run Code Online (Sandbox Code Playgroud)