为什么重复这么多次?

时间:2020-01-01 19:17:54

标签: python python-3.x python-3.6

这是代码,它基本上使用win32com实例并获取属性并设置属性。 稍后将向该类添加更多方法。

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()

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

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

1 个答案:

答案 0 :(得分:1)

让我们关注这里发生的事情:

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

self.word = ...执行尝试执行setattr(self, ...)的{​​{1}},这导致getattr(self.word, ...)尝试执行getattr(self, 'word'),最终导致递归循环。一旦达到Python's recursion limit,就会抛出getattr(self.word, 'word')。您的RecursionError块将忽略此异常,并最终通过在try...except上调用相应的方法来结束循环。

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

super()

这绕过了对属性 def __init__(self): super().__setattr__('word', win32com.client.Dispatch("Word.Application")) 的自定义__setattr__实现,因此该属性在这些方法中可用,从而避免了递归。

相关问题