Add lists to class?

Mike Meyer mwm at mired.org
Sat Sep 3 21:14:26 EDT 2005


Paolino <paolo_veronelli at tiscali.it> writes:
> Mike Meyer wrote:
>> "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']
>> []
>>
> and 2c more to use attributes but prevent overriding of real attributes
>
>     def __getattr__(self,name):
>       if name in self:
>         return self[name]
>       raise AttributeError

Good point. The problem with this is that your real attributes will
now hide things stored in the dictionary. The bugs I listed above are
all caused by trying to conflate two different name spaces: the
attributes of the object and the variables stored in it as
data. Separating them out and then layering one back on top of the
other just gives you those bugs back.

      <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