Bypassing __getattribute__ for attribute access
Chris Mellon
arkanes at gmail.com
Thu Oct 25 17:30:06 EDT 2007
On Thu, 2007-10-25 at 23:13 +0200, Bruno Desthuilliers wrote:
<snip excellent breakdown>
> > The logical next question then is how does one best add a new method
> > to this class so that future references to x.set_x() and X.set_x will
> > properly resolve? It seems the answer would be to somehow add to
> > X.__dict__ a new value, with key 'set_x', value the function set_x.
>
> Yes. Which is very simply done by just binding set_x to X.set_x. Just
> like I did above. Dynamically adding methods to classes is pretty
> straightforward, the tricky point is to dynamically add methods to
> instances, since the descriptor protocol is only triggered for class
> attributes. But you obviously found how to do it using func.__get__(obj,
> type(obj)) !-)
>
This is the greasy, getting your hands dirty way. I vastly prefer (and
reccomend) using the new module:
>>> import new
>>> class X(object):
... pass
...
>>> def bar(self):
... print self
...
>>> x = X()
>>> x.bar = new.instancemethod(bar, x, X)
>>> x.bar()
<__main__.X object at 0x87dca0c>
>>>
> >>From there on the . operator I assume would perform the binding to X
> > or x as needed on-the-fly.
>
> Yes.
>
> NB: please some guru around correct me if I said something wrong (Alex ?
> Tim ? Fredrick ? If you hear me ?)
More information about the Python-list
mailing list