Reputation: 5843
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?
Upvotes: 0
Views: 428
Reputation: 40765
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).
Upvotes: 2
Reputation: 39451
The 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
Upvotes: 1
Reputation: 117691
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
Upvotes: 2