Add lists to class?

Mike Meyer mwm at mired.org
Fri Sep 2 05:53:46 CEST 2005


"BBands" <bbands at gmail.com> writes:

> I have a list with some strings in in it, 'one', 'two' 'three' and so
> on. I would like to add lists to a class with those names. I have no
> way of knowing what will be in the list or how long the list will be in
> advance.

Others have told you how to do it. Now I'm going to tell you why you
shouldn't.

First, since you don't know the names of the attributes you added, you
can't possibly write code that references them in the normal way. So
is there really much point in making them an attribute at all?

Second, since you don't know the names of the attributes you added,
you don't know if one of more of them is going to clobber a feafure of
the class that you want to use for something else. I.e., consider:

>>> class C:
...  pass
... 
>>> c = C()
>>> print c
<__main__.C instance at 0x8270b4c>
>>> c.__str__ = 'foo'
>>> print c
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: 'str' object is not callable
>>> 

I.e. - if someone adds a __str__ attribute to your class, you won't be
able to print it any more. Not a good thing.

In general, you probably want a dictionary instead of attributes:

>>> class C(dict):
...  def __init__(self, l):
...   for i in l:
...    self[i] = []
... 
>>> c = C(['a', 'b', 'c'])
>>> c['a']
[]
>>> 

You didn't say why you wanted to do this; maybe you really do have a
good reason. But that would be an exceptional case.

     <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list