OOP in Python

Alex Martelli aleaxit at yahoo.com
Wed Jun 20 15:14:15 EDT 2001


"Jonas Bengtsson" <jonas.b at home.se> wrote in message
news:4e2ddb70.0106200954.11faa218 at posting.google.com...
> Ok I admit - I am a Python-newbie!
>
> What about local variables and class variables when dealing with
> classes?
> With local vars I mean temporaryly used variables in a function. Will
> they be treated as 'normal' instance attributes? Do I have to delete
> them by myself when I'm leaving a function?

No, local variables are local, and go away as soon as the function
terminates.

> With class vars I mean if many class instances of a class may share a
> variable. In C++ this is accomplished by a static variable. How do I
> do in Python?

A class may have attributes (it's also possible to use a module
attribute, aka 'global variable', of course).  Example:

class Totalizer:
    grand_total = 0
    def inc(self):
        self.__class__.grand_total += 1
    def dec(self):
        self.__class__.grand_total -= 1
    def __str__(self):
        return "Total is %d"%self.__class__.grand_total

# two separate instances
one = Totalizer()
two = Totalizer()

# but they share state!  Try:
one.inc()
two.inc()
one.inc()
two.inc()
print one


You may choose to spell the shared-variable access as
Totalizer.grand_total += 1, but that relies on Totalizer
being a global name.  The way I've chose to spell it
breaks the sharing if separate classes inherit from
Totalizer -- you may choose either semantics.


Alex






More information about the Python-list mailing list