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