如果我有这个:
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=" ")
我之前已经定义了列表,因此oneFunction(列表)可以很好地工作.
我的问题是在第6行调用单词.我试图用相同的单词= random.choice(lists [category])定义在第一个函数之外定义单词,但这使得单词总是相同的,即使我调用oneFunction(列表) ).
我希望每次调用第一个函数然后第二个函数都有不同的单词.
如果不在oneFunction(列表)之外定义该单词,我可以这样做吗?
解决方法:
是的,您应该考虑在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返回单词,以便您可以在anotherFunction中使用oneFunction而不是word
>>> 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))
标签:python,variables,function
来源: https://codeday.me/bug/20190916/1806698.html