考虑这个类:
class foo(object):
pass
默认的字符串表示形式如下所示:
>>> str(foo)
"<class '__main__.foo'>"
如何使其显示自定义字符串?
See How to print instances of a class using print()? https://stackoverflow.com/questions/1535327 for the corresponding question about instances of the class.
In fact, this question is really a special case of that one - because in Python, classes are themselves also objects belonging to their own class - but it's not directly obvious how to apply the advice, since the default "class of classes" is pre-defined.
实施__str__() https://docs.python.org/3/reference/datamodel.html#object.__str__ or __repr__() https://docs.python.org/3/reference/datamodel.html#object.__repr__在类的元类中。
class MC(type):
def __repr__(self):
return 'Wahaha!'
class C(object):
__metaclass__ = MC
print(C)
Use __str__
如果您的意思是可读的字符串化,请使用__repr__
以获得明确的表述。
编辑:Python 3 版本
class MC(type):
def __repr__(self):
return 'Wahaha!'
class C(object, metaclass=MC):
pass
print(C)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)