A little background - I am playing around with pygame, and want to create a dictionary of all Mob class instances' positions.
The way I see it:
human = Mob(pos)
mob_positions = {human : pos}
So every time I call Mob.__init__() I wanted to add a pos to mob_positions dict.
How do I access current instance variable name? Or is it extremely wrong approach?
3 Answers 3
Any bound method, including __init__, takes at least one parameter, usually named self, which is exactly what you are describing.
class Mob(object):
def __init__(self, pos):
mob_positions[self] = pos
2 Comments
You have several ways to solve the problem. One of them is to pass mob_positions dictionary as argument to __init__.
class Mob(object):
def __init__(self, pos, field=None):
...
if field:
field[self] = pos
Such notation allows you to place mobs on initialization or not (depending on what you're doing with mobs).
2 Comments
{<Mob sprite(in 0 groups)>: pos}. ThanksThe current instance variable is simply the first argument to the function. By convention it is named self.
Here's how I'd do things.
class Mob(object):
def __init__(self, pos, mob_positions):
self.pos = pos
mob_positions[self] = pos