0

I am trying to invoke some methods defined in testlib.py, confused why there is additional 'None' in output? Thanks.

Code where I invoke testlib.py

print testlib.globalFoo()
f = testlib.Foo()
print f.getValue()

testlib.py

class Foo:
    def __init__(self):
        pass
    def getValue(self):
        print 'get value in class Foo'

def globalFoo():
    print 'in global foo'

Output,

in global foo
None <= confusion here
get value in class Foo
None <= confusion here
Lin Ma
  • 9,739
  • 32
  • 105
  • 175

3 Answers3

2

The cause is that you are printing the result of a function that doesn't return anything and only has a print statement. Any function that doesn't explicitly return something will implicitly return None.

>>> def say_hello():
...   print 'hello!'
... 
>>> print say_hello()
hello!
None
>>> h = say_hello()
hello!
>>> print h
None
>>> 
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
1

When you call print testlib.globalFoo(), the function itself is doing the printing (specifically "in global foo"). Then, the function returns nothing (or None), and that is what your print is showing. If you're only wanting to print once, simply call the function with testlib.globalFoo(), or change the function as below.

def globalFoo():
    return "the string you want to print"

The answer is the same for the other function in the class.

CDspace
  • 2,639
  • 18
  • 30
  • 36
1

When in the globalFoo() function: It not only prints out "in global foo", the function also returns a 'None'

This returned value of None is supplied to your print statement:
    print testlib.globalFoo() is actually:
    print 'None' 

when you call testlib.globalFoo(), within the function, it correctly prints 'in global foo'.

The other none is similarly from the returned value of getValue(), which returns 'None'.

Ipstone
  • 86
  • 1
  • 4