如何让Python类返回一些数据而不是它的对象地址

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对象.

Aar*_*all 8

__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)


unu*_*tbu 7

定义__repr__.

def __repr__(self):
    return str(self._x)
Run Code Online (Sandbox Code Playgroud)

Python解释器repr默认打印对象.