[Tutor] How to make comparison work
Peter Otten
__peter__ at web.de
Fri Apr 11 10:32:21 CEST 2014
Gregg Martinson wrote:
> I have been working through a fairly simple process to teach myself python
> and I am running into a problem with a comparison. Can anyone tell me
> where I am going wrong?
>
> #!/usr/bin/env python
>
> class Team(object):
> code = ""
> opponents_debated=[]
> wins=0
> losses=0
> competitors=[]
Defining the 'competitors' list here means that it is shared by all Team
instances. As soon as any team A has debated with a team B B is added to
this list. As any team immediately adds itself to the list no debate will
ever take place.
Solution: instead of a class attribute make the list an instance attribute
by moving the definition into the initialiser:
>
> def __init__(self, code):
self.competitors = []
> self.code = code
> self.competitors.append(code)
> #self.school_teams.append(code)
Note that the difference between class and instance attributes exists for
all attributes, but may not lead to an error when you rebind instead of
mutating the attribute:
>>> class T:
... wins = 0
... def win(self):
... self.wins = self.wins + 1
...
>>> a = T()
>>> b = T()
>>> a.win()
>>> a.win()
>>> b.win()
>>> a.wins
2
>>> b.wins
1
>>> T.wins
0
That is because the first time win() is called on an instance
self.wins = self.wins + 1
The instance attribute is not found and the right side falls back to look up
self.wins in the class, i. e. the first time you are effectively running
self.wins = T.wins + 1
The left-hand side always denotes an assignment to the instance, so T.wins
will always remain 0.
It is still good practice to define all attributes that are meant to be
instance attributes in the initialiser:
class Team:
def __init__(self, code):
self.wins = 0
self.losses = 0
...
More information about the Tutor
mailing list