0

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

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Well, it takes however many parameters you define it to take. But it does take at least one.
@IgnacioVazquez-Abrams: I changed my wording.
2

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

Right, I guess I was confused by result of the print, dictionary dump after using self was {<Mob sprite(in 0 groups)>: pos}. Thanks
<Mob sprite(in 0 groups)> is just a representation of your object. You just need to override __repr__() method of your mob class to receive some meningful representation (e.g. mob's name or mob's number, or smth. else you want to distinct mobs with).
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.