我可以为类而不是实例定义 __repr__ 吗?
我可以为类而不是实例定义 __repr__
吗?例如,我正在尝试执行此操作,
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 的元类生成很多类。我想要一种比库存代表更易读的方式来识别类别。
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
What I get is
In [58]: a=A()
In [59]: a
Out[59]: My class <class '__main__.A'>
In [60]: A
Out[60]: __main__.A
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要在元类上定义
__repr__
。__repr__
返回对象实例的表示形式。因此,通过在A
上定义__repr__
,您可以指定repr(A())
的外观。要定义类的表示,您需要定义
type
实例的表示方式。在这种情况下,请将type
替换为根据需要定义的__repr__
的自定义元类。如果你想为每个类定义一个自定义的 __repr__ ,我不确定是否有一种特别干净的方法来做到这一点。但你可以做这样的事情。
然后您可以根据每个班级进行自定义。
You need to define
__repr__
on the metaclass.__repr__
returns a representation of an instance of an object. So by defining__repr__
onA
, you're specifying what you wantrepr(A())
to look like.To define the representation of the class, you need to define how an instance of
type
is represented. In this case, replacetype
with a custom metaclass with__repr__
defined as you need.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.Then you can customize on a per-class basis.
当然,我在这里用通过
repr
测试的__repr__
进行演示。并演示:
Python 2:
或者 Python 3:
或者相当普遍:
并且进行
repr
测试:什么是
repr
测试?这是来自repr
文档的上述测试:Sure, I demonstrate here, with a
__repr__
that passes therepr
test.And to demonstrate:
Either Python 2:
Or Python 3:
Or fairly universally:
And to do the
repr
test:What is the
repr
test? It's the above test from the documentation onrepr
: