Decorator metaclass

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat May 24 22:50:40 EDT 2008


En Fri, 23 May 2008 16:25:19 -0300, Thomas Karolski <Thomas.Karolski at googlemail.com> escribió:

> Turns out the first msg I sent did not reach the list, so I'll just post
> what I've achieved by now:

[snip a couple of long metaclasses]

> Now the reason why I'm using decorators, is because I want to be ably to
> add the functionality dynamicly - without the need of construction
> classes for the different possibilities. Composite pattern does not help
> in this case, since I lose the ability to choose in what order I call
> the decorator's and the decorated's methods.

I haven't looked in detail to your code, but if that is what you want, you don't need a Decorator metaclass at all. Just add/replace the desired methods inside the class itself (Python is a dynamic language, remember).

py> class A(object):
...   def foo(self): print "In foo, self=", self
...
py> def bar(self): print "In bar, self=", self
...
py> a = A()
py> a.foo()
In foo, self= <__main__.A object at 0x00A3CD50>
py>
py> A.bar = bar
py> a.bar
<bound method A.bar of <__main__.A object at 0x00A3CD50>>
py> a.bar()
In bar, self= <__main__.A object at 0x00A3CD50>

You can even add methods to individual instances:

py> def baz(self): print "In baz, self=", self
...
py> import new
py> b = A()
py> b.baz = new.instancemethod(baz, b, type(b))
py> a.baz()
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'baz'
py> b.baz
<bound method A.baz of <__main__.A object at 0x00A3CDD0>>
py> b.baz()
In baz, self= <__main__.A object at 0x00A3CDD0>

-- 
Gabriel Genellina




More information about the Python-list mailing list