【问题标题】:How to get Python Class to Return Some Data and not its Object Address如何让 Python 类返回一些数据而不是它的对象地址
【发布时间】:2014-03-20 16:51:08
【问题描述】:

上下文:

使用以下内容:

class test:
    def __init__(self):
        self._x = 2

    def __str__(self):
        return str(self._x)

    def __call__(self):
        return self._x

然后用t = test()创建一个实例

我知道如何使用__str__ 进行打印:

>>> print t
2

我可以看到如何使用 __call__ 使对象可调用

>>> t()
2

问题

但是如何让对象返回一个内部属性,这样当你进入时:

>>> t
2

代替:

<__main__.test instance at 0x000000000ABC6108>

以类似于Pandas 打印出DataFrame 对象的方式。

【问题讨论】:

    标签: python oop methods pandas representation


    【解决方案1】:

    使用目录。尤其是在 cli 中,dir(t) 会尽可能多地显示您需要了解的对象 t。

    【讨论】:

      【解决方案2】:

      Define __repr__.

      def __repr__(self):
          return str(self._x)
      

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

      【讨论】:

      • 下次看到你来,我等着;)
      【解决方案3】:

      __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
      

      【讨论】:

      • 感谢 Aaron 提供更多信息
      猜你喜欢
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      • 2014-08-20
      • 1970-01-01
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多