Custom Search

Sunday, December 12, 2010

Python static class data and static class methods

Python Django static class data and static class methods

Static Data
========
simply define a class attribute. To assign a new value to the attribute, you have to
explicitly use the class name in the assignment:

class C:
count = 0 # number of times C.__init__ called

def __init__(self):
C.count = C.count + 1

def getcount(self):
return C.count # or return self.count

c.count also refers to C.count for any c such that isinstance(c, C) holds, unless
overridden by c itself or by some class on the base-class search path from c.__class__
back to C.

Caution:
-----------
within a method of C, an assignment like self.count = 42 creates a new and unrelated
instance vrbl named "count" in self's own dict. Rebinding of a class-static data name
must
always specify the class whether inside a method or not:

* Use class name to access class-static data, inside a method or not:

C.count = 314


Static methods
===========
Static methods are possible when you're using new-style classes:

class C:
def static(arg1, arg2, arg3):
# No 'self' parameter!
...
static = staticmethod(static)

However, a far more straightforward way to get the effect of a static method is via a
simple module-level function:

def getcount():
return C.count

If your code is structured so as to define one class (or tightly related class hierarchy)
per module, this supplies the desired encapsulation.

No comments:

Post a Comment