从另一个函数调用一个函数内部定义的变量

JNa*_*Nat 18 python variables function

如果我有这个:

def oneFunction(lists):
    category=random.choice(list(lists.keys()))
    word=random.choice(lists[category])

def anotherFunction():
    for letter in word:              #problem is here
        print("_",end=" ")
Run Code Online (Sandbox Code Playgroud)

我之前已经定义过lists,所以oneFunction(lists)效果很好.

我的问题是word在第6行调用.我试图word在第一个函数外面word=random.choice(lists[category])定义相同的定义,但word即使我调用它也总是相同的oneFunction(lists).

我想能够,每次我调用第一个函数,然后第二个函数,有一个不同的word.

如果word不在外面定义,我可以这样做oneFunction(lists)吗?

Abh*_*jit 36

是的,您应该考虑在Class中定义函数,并将word作为成员.这比较干净

class Spam:
    def oneFunction(self,lists):
        category=random.choice(list(lists.keys()))
        self.word=random.choice(lists[category])

    def anotherFunction(self):
        for letter in self.word:              
        print("_",end=" ")
Run Code Online (Sandbox Code Playgroud)

创建类后,必须将其实例化为Object并访问成员函数.

s = Spam()
s.oneFunction(lists)
s.anotherFunction()
Run Code Online (Sandbox Code Playgroud)

另一种方法是oneFunction返回单词,以便您可以使用oneFunction而不是单词anotherFunction

>>> def oneFunction(lists):
        category=random.choice(list(lists.keys()))
        return random.choice(lists[category])


>>> def anotherFunction():
        for letter in oneFunction(lists):              
        print("_",end=" ")
Run Code Online (Sandbox Code Playgroud)

最后,你也可以anotherFunction接受word作为参数,你可以从调用的结果中传递出来oneFunction

>>> def anotherFunction(words):
        for letter in words:              
        print("_",end=" ")
>>> anotherFunction(oneFunction(lists))
Run Code Online (Sandbox Code Playgroud)


小智 16

python中的所有内容都被视为对象,因此函数也是对象.所以你也可以使用这个方法.

def fun1():
    fun1.var = 100
    print(fun1.var)

def fun2():
    print(fun1.var)

fun1()
fun2()

print(fun1.var)
Run Code Online (Sandbox Code Playgroud)


小智 9

最简单的选择是使用全局变量。然后创建一个获取当前单词的函数。

请注意,要读取函数内的全局变量,不需要使用关键字global。但是,要写入函数内的全局变量,必须global在函数内的变量声明前面使用关键字,否则函数会将其视为单独的局部变量,并且在您写入时不会更新全局变量写信给它。

current_word = ''
def oneFunction(lists):
    global current_word
    word=random.choice(lists[category])
    current_word = word
    
def anotherFunction():
    for letter in get_word():              
          print("_",end=" ")

 def get_word():
      return current_word
Run Code Online (Sandbox Code Playgroud)

这样做的好处是,也许您的函数位于不同的模块中并且需要访问该变量。