[Tutor] class variables

Nick Lunt nick at javacat.f2s.com
Thu Jun 24 15:40:00 EDT 2004

Aha, the penny has dropped :)

Now I see how it can be useful I can understand it much better.
In the example you've given Jeremy I see that here:

>>>class beer:
>>>	beers = 0
>>>	def __init__(self):
>>>		self.make = 'murphys'
>>>		beer.beers += 1

beer.beers can be used as a static variable. Superb. I get it know :)

Thanks very much everyone for your help.


-----Original Message-----
From: tutor-bounces+nick=javacat.f2s.com at python.org
[mailto:tutor-bounces+nick=javacat.f2s.com at python.org]On Behalf Of
Adelein and Jeremy
Sent: 23 June 2004 22:46
To: tutor at python.org
Subject: Re: [Tutor] class variables

--- Nick Lunt <nick at javacat.f2s.com> 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 ?

In this example, there is no use. Once __init__ has been called and
executed, the variable cans will be taking up memory space with no
way for you to access it (well, normally, anyway). Given that x =
Beer(), neither x.cans nor Beer.cans is going to turn up anything but
an AttributeError exception. On what page are you?

Perhaps you are referring to something such as the following:

class Beer:
    beers = 0
    def __init__(self, make=''):
        self.make = make
        Beer.beers += 1

x = Beer('michelob')
y = Beer('murphys')
z = Beer('busch')

After this, the variable beers is 3, and x.beers, y.beers, z.beers,
and Beer.beers will all be 3. This, of course, is very useful.

- Jeremy

Do you Yahoo!?
New and Improved Yahoo! Mail - 100MB free storage!

Tutor maillist  -  Tutor at python.org

More information about the Tutor mailing list