Re: [Tutor] class variables

Magnus Lycka magnus at thinkware.se
Wed Jun 23 15:54:53 EDT 2004


Nick Lunt wrote:
> Hi folks,
> 
> Im making my way through the book 'Learning Python 2nd Edition'. I 
> understand classes but I have a question.
> Take the following for example -
> 
> class beer:
>     def __init__(self):
>        self.make = 'murphys'
>        cans = 4
> 
> There's several examples I've seen where 'self.var' isn't used, just 
> 'var' is, as in 'cans' above.
> I know that each instance of 'beer' will have its own value for 'make' 
> but what is the use of 'cans' without using self ?

It's simply a local variable in the function. In this case it's
completely pointless, since you just assign to it and then the 
function ends! Compare it with

def init():
    global make
    make = 'murphys'
    cans = 4

Note that class variables, i.e. variables defined in the scope of the
class, is something completely different. Like this:

class Beer:
    cans = 4
    def __init__(self):
        self.make = 'murphys'
        a_local = 5

The class varaible Beer.cans is shared between all instances of the class.
There is a separate instance variable self.make for each instance of the
Beer class. The local varable only exists during the duration of the
execution of the __init__ method. Note that instance varables hide class
varaibles.

>>> class Beer:
        cans = 4
        def __init__(self):
                self.make = 'murphys'


>>> a = Beer()
>>> b = Beer()
>>> a.make, a.cans
('murphys', 4)
>>> b.make, b.cans
('murphys', 4)
>>> a.make = 'Utenos'
>>> a.make, a.cans
('Utenos', 4)
>>> b.make, b.cans
('murphys', 4)
>>> Beer.cans = 6
>>> a.make, a.cans
('Utenos', 6)
>>> b.make, b.cans
('murphys', 6)
>>> b.cans = 3
>>> b.make, b.cans
('murphys', 3)
>>> del b.cans
>>> b.make, b.cans
('murphys', 6)
>>> 

-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus at thinkware.se



More information about the Tutor mailing list