Static class attributes

Erik Max Francis max at alcyone.com
Sun Dec 8 22:32:42 EST 2002


Timothy Grant wrote:

> Is there now a good way to create class static attributes? (e.g., an
> attribute that is shared across all classes of a given type?) In the
> past I have used Module level variables to simulate this behaviour,
> but
> It looks as if staticmethod, classmethod and property may change the
> way
> I approach this problem, but I'm not yet sure.

If you want class static _attributes_, that's easy, and has been in
Python for a long, long time.  Just do an assignment in class scope:

>>> class C:
...  S = 'hello'
...  def __init__(self, x):
...   self.x = x
... 
>>> C.S # the class attribute
'hello'
>>> c1 = C('one')
>>> c2 = C('two')
>>> c1.S # can access it through the instances, too
'hello'
>>> c2.S
'hello'
>>> c2.S = 'goodbye' # can even override it in one of the instances
>>> C.S
'hello'
>>> c1.S
'hello'

staticmethod is used when you don't want a first argument and want the
method callable either from instances or from the class itself:

>>> class D:
...  def f(x, y): # note: no self argument
...   print x, y
...  f = staticmethod(f) # this is how you transform the method
... 
>>> D.f(1, 2) # you can call it from the class
1 2
>>> d = D()
>>> d.f(3, 4) # or from an instance
3 4

classmethod is similar to staticmethod in that it allows the method to
be called either from an instance or the class itself, but it supports
an implicit first argument which is the _class_ involved, rather than
the instance:

>>> class E:
...  def g(cls, x): # note first argument will be the class
...   print repr(cls), x
...  g = classmethod(g)
... 
>>> E.g(1) # can call from the class
<class __main__.E at 0x815ce8c> 1
>>> e = E()
>>> e.g(2) # or the instance
<class __main__.E at 0x815ce8c> 2

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ The main thing in life is not to be afraid of being human.
\__/ Pablo Casals
    Kepler's laws / http://www.alcyone.com/max/physics/kepler/
 A proof of Kepler's laws.



More information about the Python-list mailing list