Pao*_*olo 5 python class instance representation
我知道有方法__repr__和__str__存在来给出类实例的正式和非正式表示.但是对于类对象是否也存在等价物,因此当打印类对象时,可以显示它的一个很好的表示?
>>> class Foo:
... def __str__(self):
... return "instance of class Foo"
...
>>> foo = Foo()
>>> print foo
instance of class Foo
>>> print Foo
__main__.Foo
Run Code Online (Sandbox Code Playgroud)
当你打电话print(foo),foo的__str__方法被调用.__str__在类中找到foo,即Foo.
同样,当你调用print(Foo),Foo的__str__方法被调用.__str__在类中找到,Foo通常是type.您可以使用元类更改它:
class FooType(type):
def __str__(cls):
return 'Me a Foo'
def __repr__(cls):
return '<Foo>'
class Foo(object):
__metaclass__=FooType
def __str__(self):
return "instance of class Foo"
print(Foo)
# Me a Foo
print(repr(Foo))
# <Foo>
Run Code Online (Sandbox Code Playgroud)