decorating container types (Python 2.4)
James Stroud
jstroud at mbi.ucla.edu
Fri Oct 12 18:57:54 EDT 2007
I was thinking that only one longmeta is really needed and its not
necessary to make a new metaclass at each go:
from types import MethodType
class longmeta(type):
def __new__(cls, *args, **kwargs):
if len(args) == 2:
newcls = type.__new__(cls, args[1], (), {})
len_func = args[0].__len__.im_func
newcls.len_dlgt = MethodType(len_func, newcls, cls)
return newcls
else:
return type.__new__(cls, *args, **kwargs)
def __len__(cls):
return cls.len_dlgt()
E.g.:
py> from types import MethodType
py>
py> class longmeta(type):
... def __new__(cls, *args, **kwargs):
... if len(args) == 2:
... newcls = type.__new__(cls, args[1], (), {})
... len_func = args[0].__len__.im_func
... newcls.len_dlgt = MethodType(len_func, newcls, cls)
... return newcls
... else:
... return type.__new__(cls, *args, **kwargs)
... def __len__(cls):
... return cls.len_dlgt()
...
py> class A(object):
... value = 5
... def __len__(self):
... return A.value
...
py> a = A()
py> len(a)
5
py> B = longmeta(A, 'B')
py> len(B)
5
py> A.value = 16
py> len(B)
16
py> class C(B): pass
...
py> len(C)
16
py> A.value = 42
py> len(C)
42
James
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095
http://www.jamesstroud.com
More information about the Python-list
mailing list