如何创build一个类对象的自定义string表示?
考虑这个类:
class foo(object): pass 默认的string表示forms如下所示:
 >>> str(foo) "<class '__main__.foo'>" 
我怎样才能让这个显示一个自定义的string?
 在类的元类中实现__str__()或__repr__() 。 
 class MC(type): def __repr__(self): return 'Wahaha!' class C(object): __metaclass__ = MC print C 
 如果您的意思是可读的string化,请使用__repr__ ,使用__repr__表示无歧义的表示。 
 class foo(object): def __str__(self): return "representation" def __unicode__(self): return u"representation"