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?
Assuming you put both
.py
files in the same directory, yourPython 2.7
code runs fine with a standardCPython
interpreter such asCanopy
.Python 3.5
interpreters such as Anaconda will complain about theprint
not being used as a function and will thus not execute.Since your
print
behaves as the defaultprint
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.