[英]Using a Variable from One Function Inside Another Function then Calling It
[英]Calling variable defined inside one function from another function
如果我有這個:
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
。我試圖用相同的word=random.choice(lists[category])
定義在第一個函數之外定義word
,但這使得word
始終相同,即使我調用oneFunction(lists)
.
我希望能夠,每次我調用第一個函數,然后是第二個函數時,都有一個不同的word
。
我可以在不定義oneFunction(lists)
之外的word
的情況下執行此操作嗎?
一種方法是讓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))
最后,你可以在一個類中定義你的兩個函數,並讓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()
python中的一切都被視為對象,因此函數也是對象。 所以你也可以使用這個方法。
def fun1():
fun1.var = 100
print(fun1.var)
def fun2():
print(fun1.var)
fun1()
fun2()
print(fun1.var)
最簡單的選擇是使用全局變量。 然后創建一個獲取當前單詞的函數。
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
這樣做的好處是你的函數可能在不同的模塊中並且需要訪問變量。
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)
def oneFunction(lists):
category=random.choice(list(lists.keys()))
word=random.choice(lists[category])
return word
def anotherFunction():
for letter in word:
print("_",end=" ")
所以我繼續嘗試做我想到的事情您可以輕松地使第一個函數返回單詞,然后在另一個函數中使用該函數,同時在新函數中傳入相同的對象,如下所示:
def oneFunction(lists):
category=random.choice(list(lists.keys()))
word=random.choice(lists[category])
return word
def anotherFunction(sameList):
for letter in oneFunction(sameList):
print(letter)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.