class.__getattr__ behavior: feature or bug?
Hans Nowak
hnowak at cuci.nl
Fri Jan 14 16:40:11 EST 2000
On 14 Jan 00, at 15:12, Huayin Wang wrote:
> >>> class S:
> ... def __getattr__(self, name):
> ... if name == 'c':
> ... self.a = self.a + 1
> ... return self.a
> ... else: return None
> ...
> >>> s=S()
> >>> s
> Traceback (innermost last):
> File "<stdin>", line 1, in ?
> TypeError: call of non-function (type None)
> >>>
Feature. I think it works something like this: Typing the name of the
instance (s) in interactive mode causes Python to look for the __repr__
method (and/or __str__, possibly), because it needs a printable
representation... but it doesn't find it (since it's not defined,
obviously). So it tries to find an attribute __repr__ using __getattr__...
which returns None. Python thinks this result value should be a function
(like __repr__ is... OK, so it's actually a method... same difference), and
tries to call it. In this case, it ends up calling None, though, which
leads to an error since None isn't a function.
This should work:
class S:
def __getattr__(self, x):
return None
def __repr__(self):
return str(id(self))
I must admit this error is kinda obscure. ^_^
--Hans Nowak (zephyrfalcon at hvision.nl)
Homepage: http://fly.to/zephyrfalcon
You call me a masterless man. You are wrong. I am my own master.
More information about the Python-list
mailing list