如何将函数赋值给变量然后使用python中的参数调用

Chi*_*iko 1 python

我正在为变量分配一个函数,如下所示:

def hello(name):
    print "Hello %r \n" % name

king = hello
print "%r, King of Geeks" % king("Arthur")
Run Code Online (Sandbox Code Playgroud)

它在终端返回:

你好'
Arthur'None,极客之王

是什么赋予了?

Ale*_*x L 8

hello()是打印的东西,但返回无.(所有函数返回None,除非你在默认情况下明确return的东西)

>>> result = hello('test')
Hello 'test' 

>>> print result
None
Run Code Online (Sandbox Code Playgroud)

如果您hello()返回文本而不是打印它,您将获得预期的结果:

def hello(name):
    return "Hello %r \n" % name

king = hello
print "%r, King of Geeks" % king("Arthur")
Run Code Online (Sandbox Code Playgroud)

"你好'亚瑟'\n",极客之王

我建议使用New String Formatting而不是%:

print "{}, King of Geeks".format(king("Arthur"))
Run Code Online (Sandbox Code Playgroud)