[Tutor] object's attributes

Paul McGuire ptmcg at austin.rr.com
Fri Jan 2 19:36:42 CET 2009


Denis -

What you are seeing is standard procedure for any built-in type - no dynamic
assignment of attributes allowed.  Here is an analogous case to your
example, but based on str instead of object:

greeting = "bon jour"
greeting.language = "French"  # raises AttributeError: 'str' object has no
attribute 'language'

class I18NString(str): 
    pass
    
greeting = I18NString("bon jour")
greeting.language = "French"  # OK


The example you cited of creating a thin derived class from object, for the
simple purpose of supporting dynamically assigned attributes, sometimes goes
by the name Bag, from the Smalltalk object framework.  The Traits framework
uses a "root" class HasTraits so that you can easily attach attributes, and
then use the traits.ui package to bring up a GUI editor.

Here is a recipe from the Python Cookbook:
http://code.activestate.com/recipes/259174/
There is also the new namedtuple type in the Python 2.6 collections module,
which started out as this recipe:
http://code.activestate.com/recipes/500261/.

Happy New Year!

-- Paul





More information about the Tutor mailing list