2016-09-16 7 views
0

testlib.pyで定義されたいくつかのメソッドを呼び出そうとしていますが、出力に「なし」という追加の理由が混乱していますか?ありがとう。追加Python 2.7での出力の出力なし

私は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' 

出力

in global foo 
None <= confusion here 
get value in class Foo 
None <= confusion here 
+1

「副作用」の機能を使用する場合です。 – Nishant

答えて

2

を呼び出すコードは、原因は何も返されず、printステートメントのみを持つ関数の結果を出力していることが原因です。明示的に何かを返さない関数は暗黙的にNoneを返します。

>>> def say_hello(): 
... print 'hello!' 
... 
>>> print say_hello() 
hello! 
None 
>>> h = say_hello() 
hello! 
>>> print h 
None 
>>> 
1

あなたがprint testlib.globalFoo()を呼び出すと、関数自体は(特に「グローバルfooの中」)の印刷を行っています。その後、関数は何も返しません(またはNone)、それがあなたのプリントに表示されます。一度だけ印刷したい場合は、testlib.globalFoo()で関数を呼び出すか、以下のように関数を変更してください。

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

答えは、クラス内の他の関数と同じです。

+0

スーパーCDスペース! :) –

1

globalFoo()関数で場合: それは「グローバルFOOの」プリントアウトするだけでなく、 機能はまた、「なし」

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

を返していない他のいずれもの戻り値から同様にしませんgetValue()は、 'None'を返します。

関連する問題