我是python的初学者,有一个问题,让我很困惑。如果我先定义一个函数但在函数内我必须使用在下面另一个函数中定义的变量,我可以这样做吗?或者如何将另一个函数的返回内容导入到函数中?例如:
def hello(x,y):
good=hi(iy,ix)
"then do somethings,and use the parameter'good'."
return something
def hi(iy,ix):
"code"
return good
功能hello和范围hi是完全不同的。它们没有任何共同的变量。
请注意,调用的结果hi(x,y)是某个对象。good您使用函数中的名称保存该对象hello。
goodin中命名的变量是不同的变量,与函数中hello命名的变量无关。goodhi
它们拼写相同,但存在于不同的命名空间中。为了证明这一点,在两个函数之一中更改good变量的拼写,你会发现事情仍然有效。
编辑。追问:“那如果我想在hi函数中使用hello函数的结果怎么办?”
没有什么不寻常的。hello仔细看。
def hello(x,y):
fordf150 = hi(y,x)
"then do somethings,and use the variable 'fordf150'."
return something
def hi( ix, iy ):
"compute some value, good."
return good
一些脚本评估hello( 2, 3).
Python 创建一个新的命名空间来评估hello.
在hello,x被绑定到对象2上。绑定完成位置顺序。
在hello,y被绑定到对象3上。
在hello中,Python 计算第一条语句 ,fordf150 = hi( y, x )是y3,x是 2。
一种。Python 创建一个新的命名空间来评估hi.
湾。在hi,ix被绑定到对象3上。绑定完成位置顺序。
C。在hi,iy被绑定到对象2上。
d。在hi中,某事发生并good绑定到某个对象,例如3.1415926。
e. 在hi中,areturn被执行;将对象标识为 的值hi。在这种情况下,对象被命名为good并且是对象 3.1415926。
F。命名空间被hi丢弃。 good,ix然后iy消失。然而,对象 ( 3.1415926) 仍然是评估的值hi。
在hello中,Python 完成了第一条语句,fordf150 = hi( y, x ),y是 3,x是 2。 的值hi是 3.1415926。
一种。 fordf150绑定到通过求值创建的对象hi, 3.1415926。
在hello中,Python 继续执行其他语句。
在某些时候something绑定到一个对象,比如说,2.718281828459045。
在hello中,areturn被执行;将对象标识为 的值hello。在这种情况下,对象被命名为something并且是对象 2.718281828459045。
命名空间被丢弃。 fordf150和something消失,x和一样y。然而,对象 ( 2.718281828459045) 仍然是评估的值hello。
无论调用什么程序或脚本hello都会得到答案。
如果你想从一个函数内部定义一个变量到全局命名空间,从而让这个空间中的其他函数可以访问它,你可以使用 global 关键字。这里有一些例子
varA = 5 #A normal declaration of an integer in the main "global" namespace
def funcA():
print varA #This works, because the variable was defined in the global namespace
#and functions have read access to this.
def changeA():
varA = 2 #This however, defines a variable in the function's own namespace
#Because of this, it's not accessible by other functions.
#It has also replaced the global variable, though only inside this function
def newVar():
global varB #By using the global keyword, you assign this variable to the global namespace
varB = 5
def funcB():
print varB #Making it accessible to other functions
结论:在函数中定义的变量保留在函数的命名空间中。它仍然可以访问全局命名空间以进行只读,除非该变量已使用 global 关键字调用。
全球一词并不像乍看起来那样完全是全球性的。它实际上只是指向您正在处理的文件中最低名称空间的链接。全局关键字无法在另一个模块中访问。
作为一个温和的警告,一些人可能认为这不是“好的做法”。
您的示例程序有效,因为“好”的两个实例是不同的变量(您恰好有两个变量同名)。以下代码完全相同:
def hello(x,y):
good=hi(iy,ix)
"then do somethings,and use the parameter'good'."
return something
def hi(iy,ix):
"code"
return great
关于 python 作用域规则的更多细节在这里:
“hello”函数不介意您调用尚未定义的“hi”函数,前提是您在定义两个函数之前不要尝试实际使用“hello”函数。