{Spam?} [Tutor] class variables

Bob Gailer bgailer at alum.rpi.edu
Wed Jun 23 19:29:53 EDT 2004

At 04:42 PM 6/17/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 ?

cans is a local variable, not a class variable. It disappears when the 
__init__ method terminates. If you move the assignment to the class level, 
cans becomes a class variable; every instance of beer will have the class 
property with value 4 unless overridden.

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

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625 home
720 938 2625 cell 

More information about the Tutor mailing list