我是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
。
good
in中命名的变量是不同的变量,与函数中hello
命名的变量无关。good
hi
它们拼写相同,但存在于不同的命名空间中。为了证明这一点,在两个函数之一中更改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 )
是y
3,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”函数。