![](/img/trans.png)
[英]how do I store function variables outside of the function for use in another file?
[英]How do I use these variables outside of the function (python)?
我最近回到 Python 編程,我有一個問題。 在我的代碼中,我試圖設置插槽,但我不知道如何打印它們。
我有兩個文件,Card 和 Main。 這是主文件的代碼。
cardsList = ["dog", "fairy", "flower", 'ghost', "bow", "brain", "bird", "mountain", "glasses", "book", "water", "family", 'scream', "mask", "bacteria", "gun", "bomb", "motocycle"]
New = Card(cardsList)
New.Hand()
這一點不言自明。 這是卡片文件的代碼。
class Card(object):
cardsList = list(["dog", "fairy", "flower", 'ghost', "bow", "brain", "bird", "mountain", "glasses", "book", "water", "family", 'scream', "mask", "bacteria", "gun", "bomb", "motocycle"])
slot1 = ""
slot2 = ""
slot3 = ""
slot4 = ""
slot5 = ""
slot6 = ""
slot7 = ""
slot8 = ""
slot9 = ""
def __init__(self, cardsList):
self.cardsList = cardsList
def __len__(self):
return len(self.cardsList)
def Hand(cardsList):
return len(cardsList)
cardsList = random.shuffle(cardsList)
listTwo = []
for i in range(9):
listTwo.append(cardsList[i])
cardsList.pop(i)
return listTwo
slot1 = listTwo[1]
slot2 = listTwo[2]
slot3 = listTwo[3]
slot4 = listTwo[4]
slot5 = listTwo[5]
slot6 = listTwo[6]
slot7 = listTwo[7]
slot8 = listTwo[8]
slot9 = listTwo[9]
slots = [slot1, slot2, slot3, slot4, slot5, slot6, slot7, slot8, slot9]
print(slots)
請讓我知道如何在函數之外定義槽函數。 我需要將插槽用於不同的功能,但我不知道如何讓它們工作。
如果您還想在函數外部使用變量,則函數必須返回它們的值。
def returnSlots() :
slots = [slot1, slot2, slot3, slot4, slot5, slot6, slot7, slot8, slot9]
return slots
之后,您可以通過迭代函數來檢索每個值。
list_of_slots = []
for i in returnSlots() :
list_of_slots.append(i)
我認為這就是你想要做的:
import random
class Card(object):
def __init__(self, cardsList):
self.cardsList = cardsList
self.slot1 = ""
self.slot2 = ""
self.slot3 = ""
self.slot4 = ""
self.slot5 = ""
self.slot6 = ""
self.slot7 = ""
self.slot8 = ""
self.slot9 = ""
def __len__(self):
return len(self.cardsList)
def Hand(self):
random.shuffle(self.cardsList)
self.slot1 = cardsList[0]
self.slot2 = cardsList[1]
self.slot3 = cardsList[2]
self.slot4 = cardsList[3]
self.slot5 = cardsList[4]
self.slot6 = cardsList[5]
self.slot7 = cardsList[6]
self.slot8 = cardsList[7]
self.slot9 = cardsList[8]
cardsList = ["dog", "fairy", "flower", 'ghost', "bow", "brain", "bird", "mountain", "glasses", "book", "water", "family", 'scream', "mask", "bacteria", "gun", "bomb", "motocycle"]
myCards = Card(cardsList)
myCards.Hand()
Hand
函數會將 cardList 中的 9 張隨機卡片分配到插槽 1 到 9。 random.shuffle
, random.shuffle
將列表random.shuffle
到位,因此您不應將其分配給任何東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.