Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #38135
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: __getattr__ Confusion |
| Date | 2013-02-04 19:23 +0100 |
| Organization | None |
| References | <095a0432-f8a4-40b4-96ed-1588896fba66@googlegroups.com> <510f3a91$0$29866$c3e8da3$5496439d@news.astraweb.com> <863c89b0-2125-4525-8ad8-1111b0a6beae@googlegroups.com> <mailman.1322.1359987291.2939.python-list@python.org> <fbbc805f-b92a-42b6-adb6-7d0e1fdfab77@googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1330.1360002178.2939.python-list@python.org> (permalink) |
Saul Spatz wrote:
> Thanks, Peter. I realize this is getting sort of academic now, as I know
> how to do exactly what I want, but I'm still confused. Is __getattr__ a
> special case then, even for classic classes?
Well, it never occured to me to try a per-instance __getattr__(), but you
are about to answer your own question:
> class Adder(): # python 2.7, classic class
> def __init__(self, x):
> self.x = x
> self.__add__= lambda other: Adder(self.x+other.x)
> self.__getattr__ = lambda name: self.test(name)
>
> def __str__(self):
> return str(self.x)
>
> def test(self, name):
> print("Hello from test")
> raise AttributeError
>
> x = Adder(3)
> y = Adder(4)
> print(x+y)
> x.junk()
>
> 7
> Traceback (most recent call last):
> File "C:\Users\Saul\Documents\PythonProjects\test.py", line 18
> AttributeError: Adder instance has no attribute 'junk'
>
> Why does this work for __add__ and not for __getattr__?
I don't know, I wasn't around when these decisions were made. It could be
the initial performance tweak that would lead to a generalisation with
newstyle classes. Or it is some kind of bootstrapping issue...
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
__getattr__ Confusion Saul Spatz <saul.spatz@gmail.com> - 2013-02-03 17:08 -0800
Re: __getattr__ Confusion Chris Angelico <rosuav@gmail.com> - 2013-02-04 12:28 +1100
Re: __getattr__ Confusion Terry Reedy <tjreedy@udel.edu> - 2013-02-03 21:47 -0500
Re: __getattr__ Confusion Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-02-04 04:35 +0000
Re: __getattr__ Confusion Saul Spatz <saul.spatz@gmail.com> - 2013-02-04 05:44 -0800
Re: __getattr__ Confusion Peter Otten <__peter__@web.de> - 2013-02-04 15:15 +0100
Re: __getattr__ Confusion Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-02-05 01:46 +1100
Re: __getattr__ Confusion Saul Spatz <saul.spatz@gmail.com> - 2013-02-04 09:29 -0800
Re: __getattr__ Confusion Peter Otten <__peter__@web.de> - 2013-02-04 19:23 +0100
Re: __getattr__ Confusion Chris Angelico <rosuav@gmail.com> - 2013-02-05 12:00 +1100
Re: __getattr__ Confusion Saul Spatz <saul.spatz@gmail.com> - 2013-02-04 09:29 -0800
csiph-web