Python 类表示方法
我知道方法 __repr__
和 __str__
的存在是为了给出类实例的正式和非正式表示。但是类对象是否也存在等价物,以便在打印类对象时可以显示它的良好表示?
>>> class Foo:
... def __str__(self):
... return "instance of class Foo"
...
>>> foo = Foo()
>>> print foo
instance of class Foo
>>> print Foo
__main__.Foo
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您调用
print(foo)
时,会调用foo
的__str__
方法。__str__
位于foo
的类中,即Foo
。同样,当您调用
print(Foo)
时,会调用Foo
的__str__
方法。__str__
位于Foo
类中,通常为type
。您可以使用元类更改它:When you call
print(foo)
,foo
's__str__
method is called.__str__
is found in the class offoo
, which isFoo
.Similarly, when you call
print(Foo)
,Foo
's__str__
method is called.__str__
is found in the class ofFoo
, which is normallytype
. You can change that using a metaclass:您也许可以使用元类来做到这一点,但是据我所知,普通类没有通用的解决方案。
如果只是您自己的类,您可以采用在元数据中包含特定类变量的编码标准,即:
或者如果您使用支持类装饰器的Python,您可以使用装饰器自动为您注释它或强制元数据存在。
但是...也许你只是想要
AClass.__name__
?You might be able to do this with a metaclass, but AFAIK, there's no general solution for normal classes.
If it's just your own classes, you could adopt a coding standard of including a particular class variable with your metadata, ie:
Or if you're using a python that supports class decorators, you could use a decorator to annotate it for you automatically or enforce that the metadata is there.
But... maybe you just want
AClass.__name__
?在我看来,不能为类创建自定义
repr
字符串是件好事;类的要点是创建该类的实例。In my view, it's a good thing that you can't make a custom
repr
string for classes; the point of a class is to create instances of that class.您不能在类类型上使用
__repr__
或__str__
,但可以使用 docstring 显示有关该类的信息You cannot use the
__repr__
or__str__
on the class type but you can use the docstring to present information about the class