I'm currently learning Python and I'm very confused with its behaviour. I'm creating an instance of a class and calling it directly. It is not appearing on the shell when I'm executing the script, only when I'm calling it directly in the shell. Why does Python behave like that or is it a problem with IDLE?
Here's the code of foo.py:
class Foo:
def __init__(self, _data=None):
self.data = _data
def __repr__(self):
return "repr[%s]" % self.data
def __str__(self):
return "str[%s]" % self.data
if __name__ == "__main__":
print "Begin"
f = Foo(1234)
print "direct"
f
print "print"
print f
print "End"
Here's the shell output:
Begin
direct
print
str[1234]
End
>>> f
repr[1234]
>>>
Btw. I'm on linux (ubuntu 16.04 LTS) using IDLE 2.7.12 with Python 2.7.12
As Mr. Gordon pointed out in his comment the REPL will print the object, but in the script it won't print it out unless you tell it to do so. If you want the same type of behavior as the REPL you can do:
print(repr(f))
That should give you:
repr[1234]
Is that what you are looking for?