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

Michael Hartl mikehartl at web.de
Mon Jan 19 07:39:10 EST 2009


Phillip B Oldham schrieb:
> 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.
> --
> http://mail.python.org/mailman/listinfo/python-list
>   
You could still add the getter to the class after it has been defined if 
that's your only problem with
using a getter:

class Item(object):
  tags = ['default','item']   
 
@property
def tags(self):
    return ' '.join(self.tags)

setattr(Item, "Tags", tags)

print Item().Tags #==> default item


But I don't think there's a way to do it without a different name (here 
"tags" - "Tags"), is there?



More information about the Python-list mailing list