小编Ale*_*sov的帖子

使用property时,在__getattr__中正确处理AttributeError

我在实现属性__getattr__时遇到了困难,因此当发生错误时,会正确报告.这是我的MWE(python 3.6):

class A:

    @property
    def F(self):
        return self.moo # here should be an error

    @property
    def G(self):
        return self.F

    def __getattr__(self, name):
        print('call of __getattr__ with name =', name)
        if name == 'foo':
            return 0
        raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, name))

a = A()
print(a.G)
Run Code Online (Sandbox Code Playgroud)

输出如下:

call of __getattr__ with name = moo
call of __getattr__ with name = F
call of __getattr__ with name = G
Traceback (most recent call last):
  line 18 in …
Run Code Online (Sandbox Code Playgroud)

python

7
推荐指数
1
解决办法
1379
查看次数

标签 统计

python ×1