how to define a static field of a given class

bruno at modulix onurb at xiludom.gro
Fri Jun 2 05:47:47 EDT 2006


feel_energetic wrote:
> Hi,
> 
>     I already knew how to define a static method of a class( using
> staticmethod() ),

FWIW, it's probably one of the most useless construct in Python IMHO.
classmethod are really much more useful to me.

> but I find there isn't a built-in func to build a
> static field ( something like staticfield() )

Please define "static field", I just don't understand what it could be.

Now if what you want is a class attribute (ie: an attribute that is
shared by all instances of a class), just declare it at the class level:

class MyClass(object):
  shared_attrib = 42

# can be accessed via the class
# or via an instance
MyClass.shared_attrib
m = MyClass()
m.shared_attrib

# but you don't want to rebind it via an instance
m.shared_attrib = 33
m.shared_attrib
MyClass.shared_attrib

# note that the problem is only with rebinding - mutating is ok
class MyOtherClass(object):
  shared_attrib = [42]
mo = MyOtherClass()
mo.shared_attrib

mo.shared_attrib.append(33)
mo.shared_attrib
MyOtherClass.shared_attrib

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list