__str__() doesn't work after importing class

2019-07-29 16:58发布

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)

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?

1条回答
萌系小妹纸
2楼-- · 2019-07-29 17:14

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.

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

查看更多
登录 后发表回答