我有以下代碼:Python:調用另一個類的方法的最佳方法?
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
一個遊戲是被這個類外定義因此,此代碼不工作的陣列。 既然有可能成爲這一類中的許多其他功能,這將有可能使用一個遊戲陣列,我應該這樣做:
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字典複製到每個類中,而是通過引用傳遞參數。 – miku 2011-01-27 03:27:38