导入类后__str __()不起作用 [英] __str__() doesn't work after importing class

查看:124
本文介绍了导入类后__str __()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在导入类时遇到问题: str ()在导入类后不起作用

I encountered a problem while importing a class: the str() doesn't work after importing the class

class unit:

    value = None
    node = None

    def __init__(self,value,node):
        self.value = value
        self.node = node

    def __str__(self):
        if self.node == None:
            return str(self.value) + " -> " + "Null"
        else:
            return str(self.value) + " -> " + str(self.node.value)

在类文件中, str ()可以正常工作:

within the class file, the str() works as expected:

print unit(5,None)
5 -> Null

但是当我导入该类并在打印功能上进行测试时,它将返回对象地址,而不是预先指定的文本:

but when I import the class and test on the print function, it returns the object address instead of text pre-specified:

from unit import unit

new =  unit(5,None)
print new
<unit.unit instance at 0x000000000A8420C8>

您能帮助我了解发生了什么问题吗?

Can you help me understanding what's going wrong?

推荐答案

假设您将两个.py文件都放在同一目录中,则您的Python 2.7代码可以使用标准的CPython解释器(例如Canopy)正常运行.诸如Anaconda之类的Python 3.5解释器将抱怨<​​c5>未被用作函数,因此将不执行.

Assuming you put both .py files in the same directory, your Python 2.7 code runs fine with a standard CPython interpreter such as Canopy. Python 3.5 interpreters such as Anaconda will complain about the print not being used as a function and will thus not execute.

由于print充当对象的默认print实现,因此您需要重新编译(.pyc文件)所涉及的.py文件.通过在某些IDE中重新启动内核,可以轻松完成此操作.

Since your print behaves as the default print implementation for objects, you need to recompile (.pyc files) the involved .py files. This can easily be done by restarting your kernel in some IDE.

Canopy IDE允许您在Py​​thon解释器仍处于活动状态时再次运行.py文件.但是,在重新运行之前创建的所有对象都保持不变,并且无法神奇地获取被覆盖的__str__成员方法.

Canopy IDE allows you to run a .py file again while the Python interpreter is still active. However, all objects created before this re-run stay the same and do not magically obtain your overridden __str__ member method.

这篇关于导入类后__str __()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆