我有以下代碼:
class Player:
def __init__(self, username, trip, model):
self.username = username
self.trip = trip
self.hp = 100
#### For player moving location/room ####
def Move(self, dest):
if dest == self.loc:
return True
# Check destination room is accessible from current room
for room in aGame['rooms']:
if room['ref'] == self.loc:
for acsroom in room['acs']:
if acsroom == dest:
self.loc = dest
return True
return False
aGame是一個在此類之外定義的數組,是以此代碼不起作用.
由于這個類中可能有許多其他函數可能會使用aGame數組,我應該這樣做:
class Player:
def __init__(self, username, trip, model, aGame):
self.username = username
self.trip = trip
self.hp = 100
self.aGame = aGame
#### For player moving location/room ####
def Move(self, dest):
if dest == self.loc:
return True
# Check destination room is accessible from current room
for room in self.aGame['rooms']:
if room['ref'] == self.loc:
for acsroom in room['acs']:
if acsroom == dest:
self.loc = dest
return True
return False
或者這樣做會更好:
class Player:
def __init__(self, username, trip, model):
self.username = username
self.trip = trip
self.hp = 100
#### For player moving location/room ####
def Move(self, dest, aGame):
if dest == self.loc:
return True
# Check destination room is accessible from current room
for room in aGame['rooms']:
if room['ref'] == self.loc:
for acsroom in room['acs']:
if acsroom == dest:
self.loc = dest
return True
return False
或者我應該讓aGame成為一個全局變量(如果是這樣,如何,請注意這個類在不同的檔案中)?
由于aGame是一個遍布各處的數組,是以必須在每個類中複制它是不正确的.
我可能有這個錯誤,我正在慢慢學習OOP,謝謝你的幫助.
解決方法:
在我看來,第一個選項是正确的,因為它沒有充分的理由使用全局變量.是以選擇在第二和第三之間.
決定性的功能是,如果您想要為多個aGame值使用相同的Player執行個體.如果隻有一個值,那麼我會将它傳遞給構造函數(你的選項2)或使用gnibbler的想法使它成為一個類變量.我可能贊成将它傳遞給構造函數以便于測試.
如果您希望同一個Player執行個體可用于多個aGame值,那麼選項3可能是實作該目标的最簡潔方法.
标簽:python,oop,dictionary,global,class
來源: https://codeday.me/bug/20190630/1340332.html