我在python中将多个变量调用到另一个函数时遇到一个小问题.就像我必须在yyy()中访问xxx()变量的变量一样.帮我这样做.?
示例:
def xxx():
a=10
b=15
c=20
def yyy():
xxx()
print a ### value a from xxx()
print b ### value b from xxx()
yyy()
Run Code Online (Sandbox Code Playgroud)
从第一个函数返回它们并在第二个函数中接受它们.示例 -
def xxx():
a=10
b=15
c=20
return a,b
def yyy():
a,b = xxx()
print a ### value a from xxx()
print b ### value b from xxx()
yyy()
Run Code Online (Sandbox Code Playgroud)
你不能。在函数中创建的变量是该函数的局部变量。因此,如果您希望 functionyyy获取function中定义的某些变量的值,xxx那么您需要从 返回它们xxx,如 Sharon Dwilif K 的回答所示。请注意,变量的名称 yyy是无关紧要的;你可以写:
def yyy():
p, q = xxx()
print p ### value a from xxx()
print q ### value b from xxx()
Run Code Online (Sandbox Code Playgroud)
它会给出相同的输出。
或者,您可以创建自定义类。简而言之,类是数据以及对该数据进行操作的函数的集合。类的函数称为方法,数据项称为属性。类的每个方法都可以有自己的局部变量,但也可以访问类的属性。例如
class MyClass(object):
def xxx(self):
self.a = 10
self.b = 15
self.c = 20
def yyy(self):
self.xxx()
print self.a
print self.b
#Create an instance of the class
obj = MyClass()
obj.yyy()
Run Code Online (Sandbox Code Playgroud)
输出
10
15
Run Code Online (Sandbox Code Playgroud)
有关 Python 中的类的更多信息,请参阅链接的文档。