[Tutor] class variables
Adelein and Jeremy
adeleinandjeremy at yahoo.com
Wed Jun 23 17:46:26 EDT 2004
--- 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.
HTH
- Jeremy
__________________________________
Do you Yahoo!?
New and Improved Yahoo! Mail - 100MB free storage!
http://promotions.yahoo.com/new_mail
More information about the Tutor
mailing list