У меня есть следующий код: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 - это массив, который используется повсеместно, не представляется правильным делать копии его внутри каждого класса. Возможно, я ошибаюсь, я медленно изучаю ООП, поэтому спасибо за любую помощь.
Вы фактически не копируете * словарь 'aGame' в каждый класс - аргументы передаются« по ссылке ». – miku