Get rid of recursive call __getattr__
Peter Hansen
peter at engcorp.com
Wed Dec 14 09:56:54 EST 2005
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?
Yes. Or subclass "object" as it has a default __str__ already.
(By the way, you do realize that the NoneType message comes because your
__getattr__ is returning None, don't you? So technically you could also
return a real value (in this case a callable) and it would also work,
though it's very likely not what you wanted.
class Test:
def __getattr__(self, name):
def callable_attribute():
return 'i am attr %s' % name
return callable_attribute
>>> t = Test()
>>> print t
i am attr __str__
-Peter
More information about the Python-list
mailing list