Luke
Luke

Reputation: 5718

Variable naming in Python classes

So I started using python very recently. I am doing a small project involving classes. I for the most part have the conventions down like using self... etc. What I haven't figured out quite yet is the name mangling which may be related to my question.

Here is some code that forms a class to create a turn object that i can intilize in the beginning of a battle and allows me to switch turns periodically. (the game is going to be a pokemon battle simulator)

class turn:

    TURNS = ("player","computer")
    curr=0

    def __init__(self): 
        self.currentTurn=turn.TURNS[turn.curr]

    def getTurn(self):
        return turn.TURNS[turn.curr]

    def switch(self):
        if turn.curr == 0: 
            turn.curr = 1 
        else:   
            turn.curr = 0

        if turn.curr==0: 
            print "It's your move! \n"

        self.currentTurn=TURNS[turn.curr]

So my question is this:

Is there any feature of python that would allow me to omit the class name when referring to the class vairables. I feel like it should know to look within the class definition for those variables but it doesn't. Also, If I want to use a helper method within the same class, i seem to have to prefix that with self.

Is there anyway around this?

Upvotes: 0

Views: 109

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125078

You can reference the current class with type(self) or self.__class__. Take into account that that value changes as a class is subclassed.

So:

class turn(object):
    def __init__(self): 
        cls = type(self)
        self.currentTurn = cls.TURNS[cls.curr]

    def getTurn(self):
        cls = type(self)
        return cls.TURNS[cls.curr]

    def switch(self):
        cls = type(self)
        cls.curr = 1 - cls.curr

        if cls.curr == 0: 
            print "It's your move! \n"

        self.currentTurn = cls.TURNS[cls.curr]

but if you were to subclass turns, then setting cls.curr will be done on the subclass, not the turn parent class when you call subclass().switch().

You can also use the self.__class__ attribute, but using a built-in function lets you keep the code more readable.

However, note that as long as there are no instance attributes with the same names, you can refer to your class attributes on self as well; the following works too:

class turn(object):
    def __init__(self): 
        self.currentTurn = self.TURNS[self.curr]

    def getTurn(self):
        return self.TURNS[self.curr]

    def switch(self):
        cls = type(self)
        cls.curr = 1 - cls.curr

        if self.curr == 0: 
            print "It's your move! \n"

        self.currentTurn = self.TURNS[self.curr]

Setting class attributes still requires that you do so directly on the class, not self, however.

Upvotes: 1

Related Questions