How to mix-in __getattr__ after the fact?

dhyams dhyams at gmail.com
Mon Oct 31 08:01:40 EDT 2011


Thanks for all of the responses; everyone was exactly correct, and
obeying the binding rules for special methods did work in the example
above.  Unfortunately, I only have read-only access to the class
itself (it was a VTK class wrapped with SWIG), so I had to find
another way to accomplish what I was after.

On Oct 28, 10:26 pm, Lie Ryan <lie.1... at gmail.com> wrote:
> On 10/29/2011 05:20 AM, Ethan Furman wrote:
>
>
>
>
>
>
>
>
>
>
>
> > Python only looks up __xxx__ methods in new-style classes on the class
> > itself, not on the instances.
>
> > So this works:
>
> > 8<----------------------------------------------------------------
> > class Cow(object):
> > pass
>
> > def attrgetter(self, a):
> > print "CAUGHT: Attempting to get attribute", a
>
> > bessie = Cow()
>
> > Cow.__getattr__ = attrgetter
>
> > print bessie.milk
> > 8<----------------------------------------------------------------
>
> a minor modification might be useful:
>
> bessie = Cow()
> bessie.__class__.__getattr__ = attrgetter




More information about the Python-list mailing list