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

新手上路,请多包涵

如果我有这个:

 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) 完美运行。

My problem is calling word in line 6. I have tried to define word outside the first function with the same word=random.choice(lists[category]) definition, but that makes word 总是一样的,即使我打电话给 oneFunction(lists)

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

我可以不在 word 之外定义 oneFunction(lists) 吗?

原文由 JNat 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 211
2 个回答

One approach would be to make oneFunction return the word so that you can use oneFunction instead of word in 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 接受 word 作为参数,您可以从调用结果中传递 oneFunction

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

最后,您可以在类中定义这两个函数,并使 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=" ")

创建类后,您必须实例化一个实例并访问成员函数:

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

原文由 Abhijit 发布,翻译遵循 CC BY-SA 4.0 许可协议

python 中的一切都被视为对象,因此函数也是对象。所以你也可以使用这个方法。

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

def fun2():
    print(fun1.var)

fun1()
fun2()

print(fun1.var)

原文由 Python Learner 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题