[英]Python: __str__, but for a class, not an instance?
我理解以下Python代碼:
>>> class A(object):
... def __str__(self):
... return "An instance of the class A"
...
>>>
>>> a = A()
>>> print a
An instance of the class A
現在,我想改變輸出
>>> print A
<class '__main__.A'>
我需要哪個函數來重載才能做到這一點? 即使從未實例化類,解決方案也必須工作。 Python 2.x和3中的情況有所不同嗎?
在元類上定義__str__()
:
class A(object):
class __metaclass__(type):
def __str__(self):
return "plonk"
現在, print A
將打印plonk
。
編輯 :正如jsbueno在評論中所述,在Python 3.x中,您需要執行以下操作:
class Meta(type):
def __str__(self):
return "plonk"
class A(metaclass=Meta):
pass
即使在Python 2.x中,在類體外部定義元類也是一個更好的主意 - 我選擇上面的嵌套形式來保存一些輸入。
在元類上定義__repr__
方法:
class MetaClass(type):
def __repr__(self):
return "Customized string"
class TestClass(object):
__metaclass__ = MetaClass
print TestClass # Customized string
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.