![](/img/trans.png)
[英]is a function an instance of built-in class 'function' in python?
[英]Print Instance of Class In Python as Built-In DataType?
我正在阅读DiveIntoPython。
我想知道为什么我可以直接将UserDict的实例打印为字典。 详细来说,这些代码
import UserDict;
d = UserDict.UserDict({1:1, 'a':2});
print d;
print d.data;
将有输出
{'a': 2, 1: 1}
{'a': 2, 1: 1}
这些代码
class MyDict:
def __init__(self, dictData=None):
self.data = dictData;
d = MyDict({1:1, 'a':2});
print d;
print d.data;
将有输出(在我的机器上)
<__main__.MyDict instance at 0x10049ef80>
{'a': 2, 1: 1}
换句话说,如何定义我的类,并将其实例打印为内置数据类型? 谢谢!
对象的打印方式repr
其repr
当您从mixin继承时,它已经提供了repr
功能。 还请注意,这些天您可以直接从dict
继承。
您可以定义
def __repr__(self):
return repr(self.data)
__str__
和__repr__
之间的区别在于,大多数__str__
应该是可读且__str__
。 __repr__
它可能可以用来提供eval
“d串构建原来的对象(虽然不是必要的) -见伟大的答案这里的区别: __str__和__repr__之间的区别在Python
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.