newbie question on class vars

Sean 'Shaleh' Perry shalehperry at attbi.com
Mon Oct 7 17:12:57 EDT 2002


On Monday 07 October 2002 12:09, JXSternChangeX2R wrote:
> late bulletin:  saying "self.__gvar" inside fn1 and fn2 fixes, but I
> thought the idea was to avoid saying "self." all the time.
>

The point of placing a variable in the class instead of the instances is so 
you can have a variable global to all instances.

class Foo:
    count = 0
    def __init__(self):
        Foo.count += 1

    def __del__(self):
        Foo.count -= 1

Note to access class variables you use the class name, not the instance 
variable 'self'.

f = Foo()
d = Foo()
g = Foo()

print f.count
print d.count
print g.count

Should all print '3'.




More information about the Python-list mailing list