[Tutor] [Fwd: Re: Intercepting methods calls]

Marilyn Davis marilyn at deliberate.com
Thu Jun 5 00:18:55 CEST 2008


I keep forgetting to reply-to the list.  I wish it was the default.

On Wed, June 4, 2008 11:21 am, Andreas Kostyrka wrote:

> Simple (untested in the mailer typed):
>
>
> class A: def __getattr__(self, key): if key.startswith("user"): def func():
> return key[4:] return func raise AttributeError
>
> assert A().userabc() == "abc"
>
> Something like that?

Yes it works!  Brilliant.

You listed __init__ and I'm not sure I know what you mean.

I was thinking of not having access to the original class/method so I did
this awful thing:

a_def.py

class A:
    def SaySomething(self):
        print 'this'

____

import a_def

def SayElse(dummy=None):
    print 'that'

a_def.A.SaySomething = SayElse

a_def.A().SaySomething()

---

and 'that' came out.  I guess the A class could have been written to
prevent that from happening.

Thank you for the info and thoughts.

Marilyn Davis


>
>
>
> On Wednesday 04 June 2008 19:12:16 you wrote:
>
>> Sorry, i doesn't explain my question how i should.
>>
>>
>> What I'm trying to accomplish is to add methods dynamically at class
>> instances. but i what to create them whe a A().someMethod() is called (
>> someMethod doesn't exist )
>>
>> Like as with attributes.
>>
>>
>> So far i try with ( at instance and at class level ):
>>
>>
>> def foo(): return lambda: 'foo'
>>
>> class A(object):  pass
>>
>> a = A() a.foo = foo()
>>
>> ---------------------------
>>
>>
>> def foo(): return lambda self: 'foo'
>>
>> class A(object):  pass
>>
>> A.foo = foo()
>> a= A()
>>
>> This works, but i really like to be able of bound those functions using
>> a sintax like:
>>
>> a = A() a.someMethod()    # This should bound the somethod to a
>> function.
>>
>>
>> Thaks in advance
>>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor






More information about the Tutor mailing list