是的,您应该考虑在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类中定义函数以操作成员变量word,并展示了多种方法,如通过成员函数访问、函数返回值和参数传递。实例化类并演示了这些技巧的应用。

被折叠的 条评论
为什么被折叠?



