Python - Instance Variable Access

I am currently making a game. I have 2 classes and I want one to access the others instance variables. I'm not sure how to do this or if it is possible.

Both Classes at some point inherits to the class gameEngine
gameEngine <- Game
gameEngine <- SuperSprite <- Character <- Enemy
gameEngine <- SuperSprite <- Character <- Player

My Game class creates an instance variable of an object self.player = Player(self) and I want to be able to use that in my Enemy class so it can do self.player.x. So I can make AI in the enemy class so it’s aware of my player. Any suggestions for how to do this, my logic might be wrong so any help would be grateful. If I need to post my code or anything please tell me.

That or I have been trying to pass an object to a function. So bob can get enemyAI in the game class. But I get an error 'Enemy' object is not callable. Yet it passes it and does the function prints out information then dies. BUT if I move self.enemyAi(self.bob) into the clicked condition it works fine.

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"

-------------Problems Reply------------

If i understand you correctly, You want to have the Enermy instances get access to of the Player instance

There are 2 ways to accomplish it. I'm using the second method atm in my programs and plans to add the first method.

First way involves getting the class to have an instance, and calling a class method allows one to get that instance.

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

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

Second way to do it is what I've been working with. It involves having the Game class regulating EVERYTHING in the game. Meaning: Everything is a variable under game. Also, every single game variable (for example, a player) will have an attribute named game that reference back to the game instance.


class Player:
def __init__(self, game): = game

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
##'Pretend I have an enermy object here'
## Iin your enermy class, will be able to access the player instance, and its properties

Some might object with having the second way, I, too, see the problem with an extra step. Maybe someone can shed some light on the comparison between the 2.

A combination method could be which is what I'm hoping to move to, however this raises some issue with which one you need to place first in the file, or else you might get Player not defined or Game not defined. Though I think it can be solved with separating the 2 classes into different files.

class Player:
def __init__(self): = 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

def getInstance(cls):
return cls.instance

The error is likely the lack of a constructor for the Enemy class. By running:

self.bob = Enemy(self)

It looks for the function __init__(self, arg1) in the Enemy class. If it is not provided, Python will be unable to treat Enemy as a "callable," meaning that it cannot be used like a function, or in this case, used to call a constructor with one argument.

Category:python Views:1 Time:2011-05-01

Related post

  • Accessing Python instance variables with __dict__- Is it wrong? 2011-01-18

    If I want to access the list of instance variables of an object, I can call myObject.__dict__.keys(). I want to use this attribute to print out all instance variables of an object. I am hesitant to do this because __dict__ is a "secret" attribute, an

  • Ruby instance variable access 2012-01-11

    Just curious what the best practice is for accessing an instance variable from within a class assuming attr_accessor is set. class Test attr_accessor :user def initializer(user) @user = user end def foo @user end end or class Test attr_accessor :user

  • Are Python instance variables thread-safe? 2011-11-29

    OK, check following codes first: class DemoClass(): def __init__(self): #### I really want to know if self.Counter is thread-safe. self.Counter = 0 def Increase(self): self.Counter = self.Counter + 1 def Decrease(self): self.Counter = self.Counter -

  • instance variable access (via self) results in a null pointer dereference 2012-04-20

    Running an analysis on my app results in the logical error in the subject. I don't really know what that means. Below is a screen of the error: Thanks for anyone helping out with this. --------------Solutions------------- The path it's showing you is

  • Java Instance Variable Accessibility 2008-11-06

    What is the difference in the accessibility of the following variables in Java? public class Joe { public int a; protected int b; private int b; int c; } I'm most interested in what the last one is doing. --------------Solutions------------- public:

  • One function argument or instance variable [Clean Code book] 2010-09-11

    I'm reading Uncle Bob's "Clean Code" book and constantly finding contradictory statements. Here is one of them. Book claims that we should use as few function arguments as possible, so it's more preferably to use function without any arguments to fun

  • Differences between static and instance variables in python. Do they even exist? 2009-11-08

    A random class definition: class ABC: x = 6 Setting some values, first for the abc instance, later for the static variable: abc = ABC() abc.x = 2 ABC.x = 5 and then print the results: print abc.x print ABC.x which prints 2 5 Now, I don't really get w

  • Compound assignment to Python class and instance variables 2010-03-11

    I've been trying to understand Python's handling of class and instance variables. In particular, I found this answer quite helpful. Basically it says that if you declare a class variable, and then you do an assignment to [instance].property, you will

  • Instance variables vs. class variables in Python 2010-04-26

    I have Python classes, of which I need only one instance at runtime, so it would be sufficient to have the attributes only once per class and not per instance. If there would be more than one instance (what won't happen), all instance should have the

  • Python: How should I make instance variables available? 2010-06-03

    Suppose I have: class myclass: def __init__(self): = "bar" where the value of foo needs to be available to users of myclass. Is it OK to just read the value of foo directly from an instance of myclass? Should I add a get_foo method to myclas

  • Is it more efficient to use the keyword this when accessing instance variables? 2011-03-02

    The this keyword is optional when accessing instance fields, properties, and methods in languages like C# and Java. I've been doing some best practice research on various languages lately, and have noticed many places recommend creating a local refer

  • Python get __doc__ documentation for instance variable 2011-04-26

    In python, I know I'm supposed to document instance variables like this: self.x = 22 """docstring for x""" #: docstring for x self.x = 22 self.x = 22 #: docstring for x But I can't seem to find a way to get hold of that documentation in code. MyClass

  • python class instance variables and class variables 2012-01-02

    im having a problem understanding how class / instance variables work in python. I dont understand why when i try this code the list variable seems to be a class variable class testClass(): list = [] def __init__(self): self.list.append('thing') p =

  • Why does Python seem to treat instance variables as shared between objects? 2012-01-14

    I was working on a simple script today when I noticed a strange quirk in the way Python treats instance variables. Say we have a simple object: class Spam(object): eggs = {} def __init__(self, bacon_type): self.eggs["bacon"] = bacon_type def __str__(

  • python member variable of instance works like member variable, and some works like static variable 2012-03-20

    i'm python newbie, and member variable of class works weird in my python code. some works like normal variable, but some works like static variable! class Chaos: list_value = [] value = "default" def set_value(self, word): self.list_value.append(word

  • Python - Get Instance Variables 2008-09-20

    Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code: class hi: def __init__(self): self.ii = "foo" self.kk = "bar" Is there a way for me to do this: >>> mystery_method(hi)

  • What's a good way to keep track of class instance variables in Python? 2009-01-30

    I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a .h file that gives me a neat list (complete with comments) of all the class' members. But sinc

  • How to access instance variables from one class while inside another class 2009-02-28

    I'm really new to Ruby. And by new - less than 16 hours, but my boss gave me some Ruby code to add to. However, I found it was one giant file and not modular at all, so I decided to clean it up. Now that I've broken it up into several files/classes (

  • Static public method accessing private instance variables in Javascript 2009-03-16

    I've been reading Diaz's book Pro JavaScript Design Patterns. Great book. I myself am not a pro by any means. My question: can I have a static function that has access to private instance variables? My program has a bunch of devices, and an output of

Copyright (C), All Rights Reserved.

processed in 0.069 (s). 11 q(s)