DRY and static attribute for multiple classes.

Michele Simionato michele.simionato at gmail.com
Wed Feb 2 11:58:45 EST 2011

Notice that Peter's approach also works without inheritance:

registries = {}

def per_class(self):
   cls = type(self)
      return registries[cls]
   except KeyError:
      result = registries[cls] = []
      return result

class A(object): per_class=per_class
class B(object): per_class=per_class
assert A().per_class is A().per_class
assert B().per_class is B().per_class
assert A().per_class is not B().per_class

(you can also put the per_class property in a module and import it
class A(object): from module import per_class).

There is no need to use inheritance if you only need one method.
Notice also that if you
are working with a complex third party framework (say Django) that may
use metaclasses
or strange tricks (such as __slots__) the safer way is to avoid both
inheritance and metaclasses.


More information about the Python-list mailing list