[Tutor] Intercepting methods calls

Andreas Kostyrka andreas at kostyrka.org
Wed Jun 4 20:21:55 CEST 2008


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?


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


-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part.
URL: <http://mail.python.org/pipermail/tutor/attachments/20080604/06315efb/attachment.pgp>


More information about the Tutor mailing list