Get rid of recursive call __getattr__
Steve Holden
steve at holdenweb.com
Wed Dec 14 09:47:37 EST 2005
Peter Otten wrote:
> Pelmen wrote:
>
>
>>>>>class Test:
>>
>> def __getattr__(self, attr):
>> print attr
>>
>> def foo(x):
>> print x
>>
>>
>>>>>t = Test()
>>>>>print t
>>
>>__str__
>>
>>Traceback (most recent call last):
>> File "<pyshell#23>", line 1, in -toplevel-
>> print t
>>TypeError: 'NoneType' object is not callable
>>
>>what i have to do? define __str__ explicitly?
>
>
> By seemingly not returning anything your __getattr__() method actually
> returns None. Instead you should raise an AttributeError when your
> __getattr__() encounters the name of an attribute it doesn't handle.
> Let's assume Test.__getattr__() should implement an attribute 'alpha' and
> nothing else:
>
>
>>>>class Test:
>
> ... def __getattr__(self, name):
> ... print "looking up", name
> ... if name == "alpha":
> ... return 42
> ... print "lookup failed for", name
> ... raise AttributeError
or, rather better IMHO,
raise AttributeError("lookup failed for %s" % name)
> ...
>
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/
More information about the Python-list
mailing list