faqts : Computers : Programming : Languages : Python : Language and Syntax : Classes

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

67 of 67 people (100%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

How do I implement class variables, shared among all instances?
What is a class attribute?

Mar 10th, 2000 11:53
Steve Holden, Oleg Broytmann


Variables assigned in the class definition, rather in the method
definitions, are attributes of the class, and hence shared among
all instances of that class.
They should qualify the class name or the name of an instance.
    class Sharer:
        InstanceCount = 0          # Class attribute
        def __init__(self, val):
            Sharer.InstanceCount = Sharer.InstanceCount + 1
            self.instancenumber = Sharer.InstanceCount
            self.val = val
        def method(self):
            print "Instance", self.instancenumber, \
                    "- value is", self.val
    object1 = Sharer(1)
    object2 = Sharer("Hello there!")
    object1.method()
    object2.method()
    print object1.InstanceCount
    print object2.InstanceCount
    print Sharer.InstanceCount
The output from running this script is:
    Instance 1 - value is 1
    Instance 2 - value is Hello there!
    2
    2
    2
You can see more clearly which attributes are owned by the class
and which by instances using the dir() function.  This also serves
to highlight the fact that method definitions are in fact class
attributes:
>>> dir (Sharer)
['InstanceCount', '__doc__', '__init__', '__module__', 'method']
>>> dir(object1)
['instancenumber', 'val']