Python类表示的方法 [英] Methods for Python classes representation
问题描述
我知道存在方法 __ repr __
和 __ str __
,以给出类实例的正式和非正式表示。但是类对象也有同样的存在,所以当类对象打印时,它的一个很好的表示可以显示?
I know that methods __repr__
and __str__
exist to give a formal and informal representation of class instances. But does an equivalent exist for class objects too, so that when the class object is printed, a nice representation of it could be shown?
>>> class Foo:
... def __str__(self):
... return "instance of class Foo"
...
>>> foo = Foo()
>>> print foo
instance of class Foo
>>> print Foo
__main__.Foo
推荐答案
调用 print(foo)
, foo
' __ str __
叫做。 __ str __
位于 foo
类中, Foo
。
When you call print(foo)
, foo
's __str__
method is called. __str__
is found in the class of foo
, which is Foo
.
同样,当您调用 print(Foo)
, Foo
的 __ str __
方法被调用。 __ str __
在 Foo
类中找到,通常为 type
。您可以使用元类更改:
Similarly, when you call print(Foo)
, Foo
's __str__
method is called. __str__
is found in the class of Foo
, which is normally type
. You can change that using a metaclass:
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>
这篇关于Python类表示的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!