By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,522 Members | 1,770 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,522 IT Pros & Developers. It's quick & easy.

Decorator pattern for new-style classes ?

P: n/a
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

Jul 19 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
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

Jul 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.