为什么会重复这么多次?

Why does it repeat so many times?

这是代码,它主要使用 win32com 实例并获取属性和设置属性。 稍后将向此添加更多方法class。

import win32com.client

class WORD(object):

    def __init__(self):
        self.word = win32com.client.Dispatch("Word.Application")

    def __getattr__(self, val):
        try:
            print(1)            
            attr = getattr(self.word, val)
        except:
            print(2)
            attr = super().__getattr__(val)
        return attr

    def __setattr__(self, attr, val):
        try:
            print(3)
            setattr(self.word, attr, val)
        except:
            print(4)
            super().__setattr__(attr, val)    


app = WORD()

635次输出2,最后输出4。为什么?谢谢。

2
2
2
2
2
2
2
2
2
2
.
.
.
2
2
2
2
2
2
2
2
2
4

让我们看看这里发生了什么:

    def __init__(self):
        self.word = win32com.client.Dispatch("Word.Application")

self.word = ... 执行 setattr(self, ...),它试图做 getattr(self.word, ...),这导致 getattr(self, 'word'),它试图做 getattr(self.word, 'word'),最终在递归循环。一旦达到 Python's recursion limit,就会抛出 RecursionError。您的 try...except 块会忽略此异常并最终通过调用 super().

上的相应方法来结束循环

解决此问题并获得我猜您想要的功能的一种简单方法是按如下方式更改初始化程序:

    def __init__(self):
        super().__setattr__('word', win32com.client.Dispatch("Word.Application"))

这绕过了 属性 word 的自定义 __setattr__ 实现,因此 属性 在这些方法中可用,避免了递归。