37

私がこれを持っている場合:

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)完全に機能します。

私の問題は 6 行目の呼び出しです。最初の関数の外側で同じ定義wordを定義しようとしましたが、呼び出しても常に同じになります。wordword=random.choice(lists[category])wordoneFunction(lists)

最初の関数を呼び出してから 2 番目の関数を呼び出すたびに、異なるword.

wordの外でそれを定義せずにこれを行うことはできますoneFunction(lists)か?

4

6 に答える 6

71

1 つのアプローチは、 inの代わりにoneFunction使用できるように単語を返すようにすることです。oneFunctionwordanotherFunction

def oneFunction(lists):
    category = random.choice(list(lists.keys()))
    return random.choice(lists[category])

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

別のアプローチは、呼び出しの結果から渡すことができるパラメーターとしてanotherFunction受け入れます。wordoneFunction

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()
于 2012-04-13T11:26:35.197 に答える