Can I run an operation on an object's attribute when reading?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Jan 19 20:02:34 CET 2009


Chris Rebert a écrit :
> On Mon, Jan 19, 2009 at 4:22 AM, Phillip B Oldham
> <phillip.oldham at gmail.com> wrote:
>> On Mon, Jan 19, 2009 at 12:15 PM, Chris Rebert <clp2 at rebertia.com> wrote:
>>> Assuming I'm interpreting you correctly (you're going to have to use
>>> something like a getter):
>> Thanks, but I'm looking for a way to do it *without* using a getter as
>> I don't have easy access to the class (its being generated for me
>> elsewhere). Essentially I'd like to overwrite (if possible) the
>> default behavior when returning certain attributes on certain objects.
> 
> To my knowledge, you can't really "overwrite" that behavior without
> editing the class (or how it's generated).

Assuming it's really about a *class* object (not instances of it), *and* 
it's a new-style class, it is possible:
class Foo(object):
     def __init__(self):
         self.tags = ['foo', 'bar']

def wrap_tag_access(cls):
     def fset(obj, value):
         obj._tags = value

     def fget(obj):
         print "do something here"
         return obj._tags

     cls.tags = property(fset=fset, fget=fget)
     return cls

Foo = wrap_tag_access(Foo)
f = Foo()
print f.tags




> The next closest thing would be to write a proxy class that defines a
> __getattr__ method implementing the semantics you want.

If it's a "classic" class, then yes, it's probably the best thing to do.



More information about the Python-list mailing list