replacing instance __setattr__
Jonathan Hogg
jonathan at onegoodidea.com
Thu Jul 4 16:46:06 EDT 2002
On 4/7/2002 17:36, in article 6qfzyzxxfx.fsf at abnoba.intevation.de, "Bernhard
Herzog" <bh at intevation.de> wrote:
> I'm not sure about the new style classes as I haven't had the time to
> really look at them yet, but for old style classes that's not quite
> true.
>
> For instance, __getattr__ does *not* define how attributes are looked
> up. It's only called by the interpreter when the normal attribute lookup
> fails.
Yeah, I knew I was taking liberties when I wrote the posting, since the
whole thing is done at the C level. The __*attr__ python methods don't
actually get called until later in the process. The '__getattribute__'
special method lets you hook into attribute lookup at an earlier point so I
should have used that as an example, but it only works with new-style
classes.
On 4/7/2002 18:09, in article
mailman.1025803028.29763.python-list at python.org, "Tim Peters"
<tim.one at comcast.net> wrote:
> The object dict (x's dict in the above, which has nothing to do with
> object's dict) is never searched for methods, and not in any version of
> Python. Methods can only come from classes in Python. If the name
> "somemethod" isn't found in x's class or any of its base classes, then
> "somemethod" is not a method of x. "somemethod" may well be a data
> attribute of x that's bound to a function that "acts like" a method, or
> close enough to acting like a method that your app doesn't care about the
> difference, but even so it's not a method of x if you're careful with words.
> An object's (as opposed to the builtin class named object) dict in Python
> can only supply data attributes.
Hmmm.
>>> class foo:
... def bar( self ):
... print 'bar'
...
>>> f = foo()
>>> f.bar
<bound method foo.bar of <__main__.foo instance at 0x3f7c60>>
>>> type( f.bar )
<type 'instance method'>
>>> f.bar()
bar
>>>
>>> def baz( self ):
... print 'baz'
...
>>> import new
>>> f.baz = new.instancemethod( baz, f, foo )
>>> f.baz
<bound method foo.baz of <__main__.foo instance at 0x3f7c60>>
>>> type( f.baz )
<type 'instance method'>
>>> f.baz()
baz
>>>
Looks like a method, walks like a method - and surely, in the brave new
world of types and metaclasses, that's the only definition that counts ;-)
Jonathan
More information about the Python-list
mailing list