Python - 实例变量访问

时间:2011-05-01 01:13:23

标签: python variables object instance

我正在制作游戏。我有2个类,我想要一个访问其他实例变量。我不知道该怎么做或者是否有可能。

两个类在某些时候都继承了类gameEngine
gameEngine< - 游戏
gameEngine< - SuperSprite< - Character< - Enemy
gameEngine< - SuperSprite< - Character< - Player

我的Game类创建了一个对象self.player = Player(self)的实例变量,我希望能够在我的Enemy类中使用它,这样它就可以self.player.x。所以我可以在敌人的班级中制作AI,这样它就能识别我的玩家。关于如何做到这一点的任何建议,我的逻辑可能是错的,所以任何帮助都会感激不尽。如果我需要发布我的代码或其他任何内容,请告诉我。

那个或者我一直试图将一个对象传递给一个函数。所以bob可以在游戏类中获得enemyAI。但我得到一个错误'敌人'对象不可调用。然而它传递了它并且函数打印出信息然后死掉。但是如果我将self.enemyAi(self.bob)移动到点击状态,它就能正常工作。

if self.enemyWeakBtn.clicked:
    print "spawning enemey"
    self.bob = Enemy(self)

    self.enemies.append(self.bob)
    self.enemyGroup = self.makeSpriteGroup(self.enemies)
    self.addGroup(self.enemyGroup)
    self.enemyActive = True            

elif self.enemyActive:
    print self.bob
    self.enemyAi(self.bob)
    print " active"

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望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

有些人可能会反对第二种方式,我也是,通过额外的步骤来看问题。也许有人可以对2之间的比较有所了解。

组合方法可能就是我希望转移到的方法,但是这会引发一些问题,你需要先将哪一个放在文件中,否则你可能会得到Player未定义或Game未定义。虽然我认为可以通过将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

答案 1 :(得分:0)

错误可能是缺少Enemy类的构造函数。通过运行:

self.bob = Enemy(self)

它在__init__(self, arg1)类中查找函数Enemy。如果没有提供,Python将无法将Enemy视为“可调用”,这意味着它不能像函数一样使用,或者在这种情况下,用于调用带有一个参数的构造函数。

相关问题