pre-PEP generic objects

Peter Otten __peter__ at web.de
Thu Dec 2 06:07:00 EST 2004


Nick Craig-Wood wrote:

> Scott David Daniels <Scott.Daniels at Acm.Org> wrote:
>>  Nick Craig-Wood wrote:
>> > class Hash:
>> >     def __init__(self, **kwargs):
>> >         for key,value in kwargs.items():
>> >             setattr(self, key, value)
>> >     def __getitem__(self, x):
>> >         return getattr(self, x)
>> >     def __setitem__(self, x, y):
>> >         setattr(self, x, y)
>> 
>>  You can simplify this:
>>  class Hash(object):
>>       def __init__(self, **kwargs):
>>           for key,value in kwargs.items():
>>               setattr(self, key, value)
>>       __getitem__ = getattr
>>       __setitem__ = setattr
> 
> That doesn't work unfortunately...
> 
>>>> class Hash(object):
> ...     def __init__(self, **kwargs):
> ...         for key,value in kwargs.items():
> ...             setattr(self, key, value)
> ...     __getitem__ = getattr
> ...     __setitem__ = setattr
> ...
>>>> h=Hash(a=1,b=2)
>>>> h.a
> 1
>>>> h['a']
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: getattr expected at least 2 arguments, got 1
>>>>
> 
> I'm not exactly sure why though!

Functions written in Python have a __get__ attribute while builtin functions
(implemented in C) don't. Python-coded functions therefore automatically
act as descriptors while builtins are just another attribute. See

http://mail.python.org/pipermail/python-list/2004-May/219424.html

for a strange example.

Peter





More information about the Python-list mailing list