Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Automatic class attribute

3 views
Skip to first unread message

Franck PEREZ

unread,
Feb 3, 2006, 5:28:08 PM2/3/06
to pytho...@python.org
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

Kirk McDonald

unread,
Feb 3, 2006, 5:49:27 PM2/3/06
to

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

Franck PEREZ

unread,
Feb 3, 2006, 10:44:28 PM2/3/06
to pytho...@python.org
> --
> http://mail.python.org/mailman/listinfo/python-list
>


Works great. Thanks a lot.

0 new messages