다음 코드가 있습니다.파이썬 : 다른 클래스의 메소드를 호출하는 가장 좋은 방법은?
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' 사전을 각 클래스에 실제로 복사하지 않습니다 - 인수는 "참조로"전달됩니다. – miku