Python equivalent of Ruby's 'method_missing'

后端 未结 4 1119
旧巷少年郎
旧巷少年郎 2020-12-29 04:10

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 interc

4条回答
  •  盖世英雄少女心
    2020-12-29 04:41

    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__.

提交回复
热议问题