What is Python's equivalent of Ruby's method_missing
method? I tried using __getattr__
but this hook applies to fields too. I only want to intercept the method invocations. What is the Python way to do it?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
You could implement a missing_method like feature in the below way:
https://gist.github.com/gterzian/6400170
Python doesn't distinguish between methods and attributes (a.k.a. "instance variables") the way Ruby does. Methods and other object attributes are looked up in exactly the same way in Python -- not even Python knows the difference at the look-up stage. Until the attribute is found, it's just a string.
So if you're asking for a way to ensure that
__getattr__
is only called for methods, I'm afraid you probably won't find an elegant solution. But it's easy enough to simply return a function (or even a brand-new dynamically bound method) from__getattr__
.There is no difference in Python between properties and methods. A method is just a property, whose type is just
instancemethod
, that happens to be callable (supports__call__
).If you want to implement this, your
__getattr__
method should return a function (alambda
or a regulardef
, whatever suite your needs) and maybe check something after the call.Although I don't recommend it!!!!!!!!!!!!!!!!!!!!!
this sort of comes closer to implementing the behavior of calling the special method for every name that does not correspond to a callable attribute/method. Of course they still don't really have separate namespaces so it may feel a bit weird. It works by overriding
__getattribute__
which works at a lower level then__getattr__
it tries to fetch an attribute if it fails it returns a curried special method to call with the name you called it with, if it succeeds it passes it on if its callable otherwise it wraps the result with a proxy object which acts in almost exactly the same way afterwards except it implements call with your special method.It doesn't allow you to access the calling object because I couldn't think of a good way to do that without sort of leaking memory(the calling object) if it's already a non-callable attribute which you store(the only think I can think of is to start a new thread that deletes it after a minute, by then you have presumably called it unless you are using it in a closure which wouldn't be supported in that case).
Edit: I forgot callable may have some false positives.
depends on the http://pypi.python.org/pypi/ProxyTypes library