__dict__ attribute for built-in types

Patrick Maupin pmaupin at gmail.com
Thu Oct 27 23:02:57 EDT 2011


On Oct 27, 9:46 pm, candide <cand... at free.invalid> wrote:
> Le 28/10/2011 02:02, MRAB a crit :
>
>
>
> > No, built-in classes written in C have certain limitations, but why
> > would you want to do that anyway?
>
> Mainly for learning purpose and Python better understanding.
>
> Actually, I have a class of mine for drawing graphs with the Graphviz
> software. The nodes of the graph to be represented was supposed to have
> 2 attributes, say title and shortName. Now, I want to plot a graph whose
> nodes are pure string. So to fit the class interface, I was trying to
> add title and shortName attribute to every string node.

You can easily do that by subclassing a string:

class AnnotatedStr(str):
    pass

x = AnnotatedStr('Node1')
x.title = 'Title for node 1'

etc.

The fact that you subclass it (unless your subclass uses __slots__)
will give it a dict.



More information about the Python-list mailing list