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

时间:2012-04-13 11:21:24

标签: python function variables

如果我有这个:

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=" ")

我之前已定义lists,因此oneFunction(lists)完美无缺。

我的问题是在第6行调用word。我尝试在第一个函数之外使用相同的word定义定义word=random.choice(lists[category]),但这使word始终为oneFunction(lists)同样,即使我打电话给word

我希望每次调用第一个函数然后第二个函数都有不同的word

我是否可以在oneFunction(lists)

之外定义{{1}}的情况下执行此操作

6 个答案:

答案 0 :(得分:32)

是的,您应该考虑在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=" ")

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

s = Spam()
s.oneFunction(lists)
s.anotherFunction()

另一种方法是让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=" ")

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

>>> def anotherFunction(words):
        for letter in words:              
        print("_",end=" ")
>>> anotherFunction(oneFunction(lists))

答案 1 :(得分:12)

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

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

def fun2():
    print(fun1.var)

fun1()
fun2()

print(fun1.var)

答案 2 :(得分:1)

def anotherFunction(word):
    for letter in word:              
        print("_", end=" ")

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

答案 3 :(得分:1)

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

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

这样做的好处是,您的功能可能位于不同的模块中,需要访问变量。

答案 4 :(得分:0)

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

def anotherFunction():
    for letter in word:             
        print("_",end=" ")

答案 5 :(得分:0)

所以我继续尝试做我想到的事情 您可以轻松地使第一个函数返回单词,然后在另一个函数中使用该函数,同时在新函数中传入相同的对象,如下所示:

aws:PrincipalArn