k3xji a écrit :
Hi,
Is there a way to hook a function call in python? I know __getattr__
is doing for variables, it is giving us a chance before a field is
initialized.
Note that since the introduction of the "new-style" object model - that
is, in Python 2.2 -, computed attributes are better handled with the
descriptor protocol, and specially the general purpose 'property' class.
The __getattr__ hook should only be used when you want to handle read
access to an attribute that doesn't exist at all (ie : automatic
delegation etc).
Also note that a method is mostly a computed attribute (another
application of the descriptor protocol FWIW)...
Do we have same functionality for methods?
Which "functionality" ? What do you want to do ? automatically delegate
method calls, or "wrap" method calls so you can ie log them or attach
more behaviour ?
Example:
class Foo(object):
def __call_method__(self, ...) # just pseudo
print 'A method is called in object...'
f = Foo()
f.test_method()
Ok, I guess this is the second case. The answer is "decorator".
def log(func):
def _logged(*args, **kw):
print "func", func.__name__, " called with ", args, kw
return func(*args, **kw)
_logged.__name__ = "logged_%s" % func.__name__
_logged.__doc__ = func.__doc__
return _logged
class Foo(object):
@log
def method(self, yadda=None):
print "in Foo.method, yadda = ", yadda
return yadda
f = Foo()
f.method()
f.method(42)
HTH
--
http://mail.python.org/mailman/listinfo/python-list