【发布时间】:2011-06-16 07:00:58
【问题描述】:
我有以下代码:
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字典复制到每个类中——参数是“通过引用”传递的。
标签: python oop class dictionary global