使用 __getattr__ 在 Python 对象中调用对象方法

Call object method in Python object with __getattr__

我已将 __getattr__(self, name) 添加到允许我访问 __dict__ 和 return 属性的对象,但我无法再调用对象方法。

我尝试了 __ 魔术方法和 getattr() 的各种组合,但似乎没有什么可以阻止 maximum recursion depth exceeded while calling a Python object

这是当前函数。注意:"values" 而不是 dict 与将来的对象相关,所以我暂时避免使用 dict

class ParentClass():
   def __getattr__(self, prop):
        if prop not in getattr(self, "properties"):
           return # DO something here to get method, I think - self.__get__(prop)
        return getattr(self, "properties")[prop]

class SubClass():
    pass

任何建议都很好。

谢谢。

在其 Guide to Python's magic methods 中引用 Rafe Kettler:

__getattribute__(self, name) After all this, __getattribute__ fits in pretty well with its companions __setattr__ and __delattr__. However, I don’t recommend you use it. __getattribute__ can only be used with new-style classes (all classes are new-style in the newest versions of Python, and in older versions you can make a class new-style by subclassing object. It allows you to define rules for whenever an attribute’s value is accessed. It suffers from some similar infinite recursion problems as its partners-incrime (this time you call the base class’s __getattribute__ method to prevent this). It also mainly obviates the need for __getattr__, which, when __getattribute__ is implemented, only gets called if it is called explicitly or an AttributeError is raised. This method can be used (after all, it’s your choice), but I don’t recommend it because it has a small use case (it’s far more rare that we need special behavior to retrieve a value than to assign to it) and because it can be really difficult to implement bug-free.

我认为你可以通过这样做来避免魔术方法:

class ParentClass(object):
    def __getattr__(self, prop):
        if prop in self.properties:
            return self.properties[prop]
        # the property is missing, do something else...