san*_*tle 4 python oop methods representation pandas
使用以下内容:
class test:
def __init__(self):
self._x = 2
def __str__(self):
return str(self._x)
def __call__(self):
return self._x
Run Code Online (Sandbox Code Playgroud)
然后用.创建一个实例 t = test()
我看到如何__str__
用于打印:
>>> print t
2
Run Code Online (Sandbox Code Playgroud)
我可以看到如何使用可调用的对象 __call__
>>> t()
2
Run Code Online (Sandbox Code Playgroud)
但是如何让对象返回一个内部属性,以便在输入时:
>>> t
2
Run Code Online (Sandbox Code Playgroud)
代替:
<__main__.test instance at 0x000000000ABC6108>
Run Code Online (Sandbox Code Playgroud)
以类似的方式Pandas
打印出DataFrame
对象.
__repr__
旨在成为对象的文字表示.
请注意,如果您定义__repr__
,则不必定义__str__
,如果您希望它们都返回相同的内容.__repr__
是__str__
后退.
class test:
def __init__(self):
self._x = 2
def __repr__(self):
return str(self._x)
def __call__(self):
return self._x
t = test()
>>> print t
2
>>> t
2
Run Code Online (Sandbox Code Playgroud)
def __repr__(self):
return str(self._x)
Run Code Online (Sandbox Code Playgroud)
Python解释器repr
默认打印对象.