从另一个函数调用在一个函数内部定义的变量
如果我有这个:
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)
效果很好。
我的问题是word
在第6行中调用。我试图word
用相同的word=random.choice(lists[category])
定义在第一个函数之外进行定义,但是word
即使调用,它也始终相同oneFunction(lists)
。
我希望每次调用第一个函数然后再调用第二个函数时,都具有一个不同的word
。
我能做到这一点,而不界定word
外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()
另一种方法是使
oneFunction
单词返回,以便您可以使用oneFunction
而不是单词inanotherFunction
>>> 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))