我可以为类而不是实例定义__repr__吗? [英] Can I define a __repr__ for a class rather than an instance?
问题描述
我可以为类而不是实例定义__repr__
吗?例如,我正在尝试这样做
Can I define a __repr__
for a class rather than an instance? For example, I'm trying to do this
class A(object):
@classmethod
def __repr__(cls):
return 'My class %s' % cls
我得到的是
In [58]: a=A()
In [59]: a
Out[59]: My class <class '__main__.A'>
In [60]: A
Out[60]: __main__.A
我试图使第60行的输出看起来像"My Class A",而不是实例a.我想要这样做的原因是我正在使用Python的元类生成许多类.而且,与股票代表相比,我希望以一种更具可读性的方式来识别类别.
I'm trying to get the output of line 60 to look like "My Class A", not for the instance a. The reason I want to do this is I'm generating a lot of classes using Python's metaclass. And I want a more readable way to identify the class than the stock repr.
推荐答案
您需要在元类上定义__repr__
.
class Meta(type):
def __repr__(cls):
return 'My class %s' % cls.__name__
class A(object):
__metaclass__ = Meta
__repr__
返回对象实例的表示.因此,通过在A
上定义__repr__
,可以指定想要repr(A())
的外观.
__repr__
returns a representation of an instance of an object. So by defining __repr__
on A
, you're specifying what you want repr(A())
to look like.
要定义类的表示形式,您需要定义如何表示type
的实例.在这种情况下,请根据需要用定义为__repr__
的自定义元类替换type
.
To define the representation of the class, you need to define how an instance of type
is represented. In this case, replace type
with a custom metaclass with __repr__
defined as you need.
>> repr(A)
My class A
如果要为每个类定义一个自定义__repr__
,我不确定是否有特别干净的方法.但是你可以做这样的事情.
If you want to define a custom __repr__
for each class, I'm not sure there's a particularly clean way to do it. But you could do something like this.
class Meta(type):
def __repr__(cls):
if hasattr(cls, '_class_repr'):
return getattr(cls, '_class_repr')()
else:
return super(Meta, cls).__repr__()
class A(object):
__metaclass__ = Meta
@classmethod
def _class_repr(cls):
return 'My class %s' % cls.__name__
class B(object):
__metaclass__ = Meta
然后,您可以按班级进行自定义.
Then you can customize on a per-class basis.
>> repr(A)
My class A
>> repr(B)
<__main__.B object at 0xb772068c>
这篇关于我可以为类而不是实例定义__repr__吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!