Possible to tack on random stuff to objects?

Cruxic cruxic at gmail.com
Tue Feb 12 21:41:29 EST 2008


That does the trick.  Thanks, Bruno.

On Feb 12, 1:23 am, Bruno Desthuilliers <bruno.
42.desthuilli... at wtf.websiteburo.oops.com> wrote:
> Cruxic a écrit :
>
> > Is it possible to tack on arbitrary attributes to a python object?
>
> Depends on the object's class. In the common case it's possible but
> there are a couple cases - mostly builtin immutable types - where it's not.
>
> > For example:
>
> > s = 'nice 2 meet you'
> > s.isFriendly = True
>
> > In the above example Python complains on the second line with:
>
> > AttributeError: 'str' object has no attribute 'isFriendly'
>
> > Is there another way?
>
>  >>> class MyString(str): pass
> ...
>  >>> s = MyString("hello")
>  >>> s.is_friendly = True
>  >>> s
> 'hello'
>  >>>




More information about the Python-list mailing list