folks, what's wrong with this?

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Fri Apr 2 10:45:26 CEST 2010


Ani a écrit :
> Hi All:
> 
> I am just a beginner in python. Can anyone please tell me what is
> wrong with this piece of code?

Robert already addressed your problem, so I'll just comment on a couple 
other points:

> import copy
> class BaseDummyObject(object):
> 
>     def __init__(self):
>         pass

This initializer is at best useless.

>     def __getattr__(self, item):

The second parameter to __getattr__ is the name that is looked for, so 
better to name it "name" or "attrname" or...

>         try:
>             return self.__dict__.__getitem__(item)

__getitem__ - like most __magicmethods__ - provides support for the 
"subscript" operator, and as such is not supposed to be explicitely 
called (except for a couple corner cases). This should just be:

               return self.__dict__[item]


>         except KeyError:
>             print "Attribute Error: attr %s of class %s non-existent!"
> %(item,  self.__class__.__name__)

The canonical AttributeError message is "'<classname>' object has no 
attribute '<attrname>'"  - ok, doesn't matter much, but being consistent 
with the core language is usually a good idea IMHO !-)

And now for the most import point: __getattr__ is only called as a 
*last* resort. That is, after the attribute lookup mechanism will have 
tried *and failed* to find the name in the instance's __dict__.


HTH



More information about the Python-list mailing list