使用__getattr__调用特定类型的子方法?

0 投票
1 回答
984 浏览
提问于 2025-04-18 18:17

我有一个类,这个类的属性是另一个类的实例。

class Field:
    def get(self):
    def set(self, value):
    def delete(self):

class Document:
    def __init__(self):
        self.y = Field()
        self.z = True

我希望当这个父类的实例访问它的属性时,实际上是调用子类的方法。

d = Document()
d.y = 'some value'  # Calls the `set` function of the Field
d.y == 'some value'  # Calls the `get` function of the Field
del d.y  # Calls the `delete` function of the Field

还有一个条件是,我只想在属性类型是 Field 的时候才有这种行为。

我在尝试使用 __getattr__ 之类的方法时遇到了递归问题,像这样:

def __getattr__(self, key):
    if isinstance(getattr(self, key), Field):
        return getattr(self, key).get()
    return getattr(self, key)

递归的问题很明显,知道为什么会发生……但我该如何避免呢?

我在StackOverflow上已经看到了一些例子,但我还是搞不清楚怎么解决这个问题。

1 个回答

1

你所描述的内容基本上就是Python通过描述符协议来访问类属性的方式。

只需要让你的字段类里有 __get____set____delete__ 这几个方法,具体可以参考这个链接:https://docs.python.org/2/howto/descriptor.html

另外,要确保你的所有类都以 object 作为基类,否则它们会继承自旧式类,这种类在Python 2中是为了兼容性而存在的,并且自Python 2.2起就不再推荐使用了(而且完全不支持描述符协议)。

撰写回答