Python's equivalent of static member data?

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu May 8 06:22:27 EDT 2003


Bram Stolk <bram at nospam.sara.nl> wrote in 
news:20030508115752.09b9e387.bram at nospam.sara.nl:

> In C++, you can have static member data: only one instance of the data,
> shared by all instances of the class.
> 
> What is the equivalent in Python?

class C:
   data = 42

print C.data

Methods can access data either as C.data, or self.data, and can update it 
by assigning to C.data. Assigning to self.data would create an instance 
variable that would hide accessing the class variable through self.data, 
but it would still be accessible by C.data

You can also create class methods which allow you to override data members 
in a subclass, which is not something you can do easily in C++

e.g. The following accesses the correct name attribute for the class on 
which it was called.

class C:
    name = 'C class'
    def getname(cls):
        return '<%s>' % cls.name
    getname = classmethod(getname)

class SubC(C):
    name = 'SubC subclass'

>>> x = SubC()
>>> print x.getname()
<SubC subclass>
>>> print SubC.getname()
<SubC subclass>
>>> print C.getname()
<C class>
>>> 

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list