[Tutor] How to make comparison work
Gregg Martinson
gregg.martinson at gmail.com
Fri Apr 11 13:47:07 CEST 2014
Excellent. I guess I never read through the class stuff in learning
python(its a great book, but very detailed....) Now I know better!
--
http://about.me/greggmartinson
On Fri, Apr 11, 2014 at 3:32 AM, Peter Otten <__peter__ at web.de> wrote:
> 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
> ...
>
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140411/8a189dbe/attachment.html>
More information about the Tutor
mailing list