如果我理解正确的话,你想有Enermy情况下,获取到播放器实例
的访问有2种方式来完成它。我在我的程序中使用第二种方法atm,并计划添加第一种方法。
第一种方式涉及让类有一个实例,并调用一个类方法允许获取该实例。
class Game:
instance = False
def __init__(self):
if self.__class__.instance:
raise RunTimeError("Game has already been initialized.") # RunTimeError might be a bad choice, but you get the point
self.__class__.instance = self
@classmethod
def getInstance(cls):
return cls.instance
##>>> g = Game()
##>>> g
##<__main__.Game instance at 0x02A429E0>
##>>> del g
##>>> Game.getInstance()
##<__main__.Game instance at 0x02A429E0>
##>>>
## Here you can have, in your enermy class, g = Game.getInstance(). And g.player will be able to access the player instance, and its properties
第二种方法是我一直在努力。它涉及让游戏类在游戏中调节一切。含义:一切都是游戏中的变数。此外,每一个游戏变量(例如玩家)都会拥有一个名为game的属性,该属性返回到游戏实例。
例子:
class Player:
def __init__(self, game):
self.game = game
print self.game.enermy
class Game:
def __init__(self):
self.enermy = "Pretend I have an enermy object here"
self.player = Player(self)
##>>> g = Game()
##Pretend I have an enermy object here
##>>> g.player.game.enermy
##'Pretend I have an enermy object here'
##>>>
## Iin your enermy class, self.game.player will be able to access the player instance, and its properties
有些人可能会与具有第二种方式反对,我也看到了问题的额外步骤。也许有人可以对比较两者之间的关系2.
一个组合方法可能是我希望移动到,但是这提出了一些问题,你需要首先放在文件中,否则你可能会得到未定义的玩家或游戏未定义。虽然我认为它可以通过将2个类分成不同的文件来解决。
class Player:
def __init__(self):
self.game = Game.getInstance()
class Game:
instance = False
def __init__(self):
if self.__class__.instance:
raise RunTimeError("Game has already been initialized.") # RunTimeError might be a bad choice, but you get the point
self.__class__.instance = self
@classmethod
def getInstance(cls):
return cls.instance