2012-04-13 11 views
10

から1つの関数内で定義された変数を呼び出します。は、私がこれを持っている場合は別の関数

私の問題は、私は同じword=random.choice(lists[category])定義で最初の関数の外wordを定義しようとしたライン6にwordを呼び出しているが、それは私がoneFunction(lists)を呼び出す場合でも、常にword同じになります。

私は、最初の関数を呼び出すたびに、次に2番目の関数を呼び出すたびに、別のwordができるようにしたいと思います。

wordoneFunction(lists)の外に定義されていないと、これを行うことはできますか?

+2

'anotherFunction'の引数として' word'を渡さないのはなぜですか? 'def anotherFunction(word):'を考えてそれに応じて呼び出す。 –

答えて

21

はい、クラス内で両方の関数を定義し、単語をメンバーにすることを考えてください。これはきれいです

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=" ") 

クラスを作成したら、それをオブジェクトにインスタンス化してメンバー関数にアクセスする必要があります。別のアプローチは、あなたがanotherFunction

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


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

そして最後に、あなたはまた、どのパラメータとして言葉を受け入れ、anotherFunctionを作ることができるで代わりに単語のoneFunctionを使用できるように言葉を返すoneFunction作ることであろう

s = Spam() 
s.oneFunction(lists) 
s.anotherFunction() 

あなたはoneFunction

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

ありがとう! 最初のアプローチでは、「自己」の部分がしていることを正確に説明してください。それは関数の引数ですか? – JNat

+0

@JNat: 'self'は、' this'(ポインタ)や 'this'(変数)が注目すべきOOP言語で使われているのと同じように、現在のオブジェクトへの参照を与えます。 – Abhijit

+0

Pythonは私に 'self'が定義されていないと言っています...それはなぜですか?私は何かの前にいくつかのモジュールをインポートする必要がありますか? – JNat

1
def anotherFunction(word): 
    for letter in word:    
     print("_", end=" ") 

def oneFunction(lists): 
    category = random.choice(list(lists.keys())) 
    word = random.choice(lists[category]) 
    return anotherFunction(word) 
を呼び出した結果から渡すことができます
+0

変数wordを、最初の関数 'oneFunction'から他の関数​​に渡すことができます。しかし、私は他の関数を最初に置かなければならないと思いますが、 "anotherFunctionは定義されていません"というエラーが出ることは少なくなります。また、私は、あなたがfor-loopで参照した 'letter'変数で何もしていないことに気付きました –

1

最も簡単な方法は、グローバル変数を使用する方法です。 次に、現在の単語を取得する関数を作成します。

current_word = '' 
def oneFunction(lists): 
    global current_word 
    word=random.choice(lists[category]) 
    current_word = word 

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

def get_word(): 
     return current_word 

これは、関数が異なるモジュールにあり、変数にアクセスする必要があることが利点です。

4

pythonのすべてがオブジェクトとみなされるため、関数もオブジェクトです。したがって、この方法を使用することもできます。

def fun1(): 
    fun1.var = 100 
    print(fun1.var) 

def fun2(): 
    print(fun1.var) 

fun1() 
fun2() 

print(fun1.var) 
関連する問題