python - 不使用 str 方法从类中检索数据

标签 python python-2.7

我有一个名为 Collatz 的类和一个函数collatz_it它创建了该类的一个对象,我尝试使用 collatz conjucture 生成数字达到 1 的步数以及使用生成器的相应步骤直到 100 万次

import collatz
values = {}
count = 0
#collatz.collatz_it(n)

def gen():
    n = 0
    x = 0
    while True:
        yield x
        n += 1
        x = collatz.collatz_it(n)

for i in gen():
    count += 1
    values[count] = i
    print values
    if count == 1000000:
        break

如您所见,我使用给定数字的 collat​​z 猜想生成达到 1 所需的步数,并将其添加到具有相应数字的字典中但是当我打印出来时字典值,它的输出是这样的:

{1: 0}
{1: 0, 2: <collatz.Collatz instance at 0x01DCA580>}
{1: 0, 2: <collatz.Collatz instance at 0x01DCA580>, 3: <collatz.Collatz instance at 0x01DCDF58>}
{1: 0, 2: <collatz.Collatz instance at 0x01DCA580>, 3: <collatz.Collatz instance at 0x01DCDF58>, 4: <collatz.Collatz instance at 0x01DCDFA8>}
{1: 0, 2: <collatz.Collatz instance at 0x01DCA580>, 3: <collatz.Collatz instance at 0x01DCDF58>, 4: <collatz.Collatz instance at 0x01DCDFA8>, 5: <collatz.Collatz instance at 0x01DCDEB8>}
{1: 0, 2: <collatz.Collatz instance at 0x01DCA580>, 3: <collatz.Collatz instance at 0x01DCDF58>, 4: <collatz.Collatz instance at 0x01DCDFA8>, 5: <collatz.Collatz instance at 0x01DCDEB8>, 6: <collatz.Collatz instance at 0x01DCDE90>}
{1: 0, 2: <collatz.Collatz instance at 0x01DCA580>, 3: <collatz.Collatz instance at 0x01DCDF58>, 4: <collatz.Collatz instance at 0x01DCDFA8>, 5: <collatz.Collatz instance at 0x01DCDEB8>, 6: <collatz.Collatz instance at 0x01DCDE90>, 7: <collatz.Collatz instance at 0x01DE8940>}

如果我打印print i而不是print values我得到了所需的输出,这基本上是因为 print语句触发__str__类中的方法

有没有什么方法可以在不输入 <collatz.Collatz instance at 0x01DCDFA8> 的情况下将实际步骤添加到字典中? ,是否有任何类型的方法可以从 __str__ 检索数据方法使我的字典看起来像这样:

{1: 0}
{1: 0, 2: 1}
{1: 0, 2: 1, 3: 7}

最佳答案

任何 Python 容器的默认表示形式都是使用内容的 repr() 输出,而不是 str()

解决方案是您为 collat​​z.Collat​​z() 实例提供一个 __repr__ 方法(您可以对其进行猴子修补),或者使用dict 的子类,在显示内容时使用 str() 而不是 repr()

__repr__ 中的猴子修补可能很简单:

collatz.Collatz.__repr__ = collatz.Collatz.__str__

当然,如果这是您自己的代码,只需在类主体本身中定义一个 __repr__ 方法即可。

关于python - 不使用 str 方法从类中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17453331/

相关文章:

python - 重新匹配无 : Differences in Python implementation of regex?

python - 如何使用 Homebrew 升级到特定的 Python 版本?

python - 如何在不更改 Pandas 分组的情况下对数据框进行排序?

python - 导入错误: cannot import name 'ft2font' from partially initialized module 'matplotlib'

Python字典没有按顺序排列

python - 为 python 应用程序创建 DEB 文件

Python - 无法启动新线程

python-2.7 - 使用Tensorflow进行RNN回归?

python - PIL中的透明PNG结果不是透明的

python - 如何将多个身份验证 ID(例如密码和电子邮件)传递给 "webApp2_extras"用户模型的 user_create 方法?