Python Printing Function Gets Unexpected Output At Interpreter?
I have the following in a file named seta.py: def print_name(): print 'hello' I am doing the following from the interpreter: import seta and then seta.print_name I would exp
Solution 1:
To call a function you need to add ()
:
seta.print_name()
Otherwise it'll print the str
/repr
version of that function object.
Demo:
deffunc():
print"Hello, World!">>> func #Returns the repr version of function object
<function func at 0xb743cb54>
>>> repr(func)
'<function func at 0xb743cb54>'>>> print func #Equivalent to `print str(func)`
<function func at 0xb743cb54>
>>> func() #Eureka!
Hello, World!
Solution 2:
If you define a function at the interpreter, and then print the name of the function without the parens, you'll get __repr__
(representation) of the function object, because in Python, functions are objects. That's what you got, but here's a demo.
>>>deffoo():...return1...>>>print foo
<function foo at 0x1005fa398>
Parentheses call the function. The call evaluates to the returned result of the function. So when you type foo()
, that turns into 1
. But without the parentheses, you are just talking about the function itself, not the calling of it. You expected the result of calling it.
As others will point out, you meant to type seta.print_name()
.
Post a Comment for "Python Printing Function Gets Unexpected Output At Interpreter?"