Decorator pattern for new-style classes ?

G

George Sakkis

Searching the archives for something related to the title, I found a
few relevant threads (e.g. http://tinyurl.com/avyg6 or
http://tinyurl.com/b5b6v); however they don't seem to give a
satisfactory answer, so here it goes again: What's the equivalent
new-style Delegate class ?

class Delegate:
def __init__(self, principal):
self._principal = principal

def __getattr__(self,name):
return getattr(self._principal,name)

# overriden methods follow here

This delegates both normal and __special__ methods; unfortunately for
new style classes __getattr__ is not called for missing special
methods. The workarounds I saw or can think of are so ugly that I
prefer to to use an old-style class after a long time :-/

George
 
M

Michele Simionato

I have no time for a long discussion, but the code should
speak for itself:

class Container(object):
def __init__(self, content):
self.content = content
def __str__(self):
return "<Container containing %r>" % self.content

class Wrapped(object):
def __init__(self, obj):
self._obj = obj
def __getattribute__(self, name):
obj = super(Wrapped, self).__getattribute__("_obj")
return getattr(obj, name)

w = Wrapped(Container("hello"))

print w.content
print w.__str__() # works
print w # does not work as you would expect, see bug report SF 729913

The discussion around the bug report is worth reading,

Michele Simionato
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top