How can I simply inherit methods from an existing instance?
<p>below I have a very simple example of what I'm trying to do.  I want to be able to use HTMLDecorator with any other class.  Ignore the fact it's called decorator, it's just a name.</p>

<pre><code>import cgi

class ClassX(object):
  pass # ... with own __repr__

class ClassY(object):
  pass # ... with own __repr__

inst_x=ClassX()

inst_y=ClassY()

inst_z=[ i*i for i in range(25) ]

inst_b=True

class HTMLDecorator(object):
   def html(self): # an "enhanced" version of __repr__
       return cgi.escape(self.__repr__()).join(("&lt;H1&gt;","&lt;/H1&gt;"))

print HTMLDecorator(inst_x).html()
print HTMLDecorator(inst_y).html()
wrapped_z = HTMLDecorator(inst_z)
inst_z[0] += 70
wrapped_z[0] += 71
print wrapped_z.html()
print HTMLDecorator(inst_b).html()
</code></pre>

<p>Output:</p>

<pre>Traceback (most recent call last):
  File "html.py", line 21, in 
    print HTMLDecorator(inst_x).html()
TypeError: default __new__ takes no parameters</pre>

<p>Is what I'm trying to do possible?  If so, what am I doing wrong?</p>

<blockquote>
  <p>Very close, but then I lose everything from ClassX. Below is something a collegue gave me that does do the trick, but it's hideous. There has to be a better way.</p>
</blockquote>

<p>Looks like you're trying to set up some sort of proxy object scheme. That's doable, and there are better solutions than your colleague's, but first consider whether it would be easier to just patch in some extra methods. This won't work for built-in classes like <code>bool</code>, but it will for your user-defined classes:</p>

<pre><code>def HTMLDecorator (obj):
    def html ():
        sep = cgi.escape (repr (obj))
        return sep.join (("&lt;H1&gt;", "&lt;/H1&gt;"))
    obj.html = html
    return obj
</code></pre>

<p>And here is the proxy version:</p>

<pre><code>class HTMLDecorator(object):
    def __init__ (self, wrapped):
        self.__wrapped = wrapped

    def html (self):
        sep = cgi.escape (repr (self.__wrapped))
        return sep.join (("&lt;H1&gt;", "&lt;/H1&gt;"))

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

    def __setattr__ (self, name, value):
        if not name.startswith ('_HTMLDecorator__'):
            setattr (self.__wrapped, name, value)
            return
        super (HTMLDecorator, self).__setattr__ (name, value)

    def __delattr__ (self, name):
        delattr (self.__wraped, name)
</code></pre>
