如果我理解正确,您希望 Enermy 实例能够访问 Player 实例
有两种方法可以完成它。我在我的程序中使用第二种方法 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 类管理游戏中的所有内容。含义:一切都是游戏下的变量。此外,每个游戏变量(例如玩家)都有一个名为 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
有些人可能会反对采用第二种方式,我也看到了额外步骤的问题。也许有人可以对两者之间的比较有所了解。
一种组合方法可能是我希望采用的方法,但这会引发一些问题,即您需要首先将哪个方法放入文件中,否则您可能会得到 Player not defined 或 Game not defined。虽然我认为可以通过将 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