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

Chris Rebert clp2 at rebertia.com
Mon Jan 19 07:15:05 EST 2009


On Mon, Jan 19, 2009 at 4:04 AM, Phillip B Oldham
<phillip.oldham at gmail.com> wrote:
> Is it possible to automatically run an operation on a object's
> attribute when reading? For instance, if I have the following:
>
> class Item(object):
>  tags = ['default','item']
>
> item = Item()
>
> desc = item.tags
>
> When I'm reading the item.tags, I'd like to automagically have the
> value converted to a string, eg: "default item". I know I could write
> a getter to do this for me, but I'd like to avoid that if possible on
> this occasion.

Assuming I'm interpreting you correctly (you're going to have to use
something like a getter):

class Item(object):
    def __init__(self):
        self._tags = ['default', 'item']

    @property
    def tags(self):
        return ' '.join(self._tags)

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

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list