Re: Automatic class attribute



Franck PEREZ wrote:
Hello all,

Considering the following code :

class C(object):
...: observers = []
...:
...: @classmethod
...: def showObservers(cls):
...: print cls.observers

class D1(C):
...: observers = [] #could it be moved in C ?

class D2(C):
...: observers = [] #could it be moved in C ?

I want each child class of C to have it's own "observers" class attribute.

The code I provided works... but I'd like to avoid typing "observers =
[]" in each child class.

Is it possible to define something in C which would basically mean :
"for each child class, automatically bind a new list attribute called
observers" ?

Are metaclasses a way ? Is it possible to avoid them ?
Thanks a lot,
Franck

By an astounding coincidence, I was just working on a similar problem. Metaclasses can do this, no problem:

class M(type):
def __init__(cls, name, bases, dict):
cls.observers = []

def showObservers(cls):
print cls.observers

class C(object):
__metaclass__ = M

class D1(C): pass
class D2(C): pass

-Kirk McDonald
.



Relevant Pages

  • Re: Automatic class attribute
    ... I want each child class of C to have it's own "observers" class attribute. ... Metaclasses can do this, no problem: ... def showObservers: ...
    (comp.lang.python)
  • Automatic class attribute
    ... ...: def showObservers: ... I want each child class of C to have it's own "observers" class attribute. ... but I'd like to avoid typing "observers = ...
    (comp.lang.python)
  • Re: callable virtual method
    ... down the Base class interface, multiplying the number of methods by 2. ... def start ... Usually when one defines an abstract base class, one expects many people will derive from it, as opposed to only one having to write it. ... That's because the base class has hardcoded where in its implementation to call the child class method. ...
    (comp.lang.python)
  • Re: callable virtual method
    ... down the Base class interface, multiplying the number of methods by 2. ... def start ... Usually when one defines an abstract base class, one expects many people will derive from it, as opposed to only one having to write it. ... That's because the base class has hardcoded where in its implementation to call the child class method. ...
    (comp.lang.python)
  • class X < Hash ... how do I do X.new { |hash, key| ...} ?
    ... I created a child class of Hash and would like to internalize the ... def initialize ...
    (comp.lang.ruby)