方法是如何__getattribute__
使用的?
它在正常的点查找之前被调用。如果它加注AttributeError
,那么我们跟注__getattr__
。
这种方法的使用是相当罕见的。标准库中只有两个定义:
$ grep -Erl "def __getattribute__\(self" cpython/Lib | grep -v "/test/"
cpython/Lib/_threading_local.py
cpython/Lib/importlib/util.py
最佳实践
以编程方式控制对单个属性的访问的正确方法是使用property
. 类D
应该写成如下(设置器和删除器可选地复制明显的预期行为):
class D(object):
def __init__(self):
self.test2=21
@property
def test(self):
return 0.
@test.setter
def test(self, value):
'''dummy function to avoid AttributeError on setting property'''
@test.deleter
def test(self):
'''dummy function to avoid AttributeError on deleting property'''
和用法:
>>> o = D()
>>> o.test
0.0
>>> o.test = 'foo'
>>> o.test
0.0
>>> del o.test
>>> o.test
0.0
属性是一个数据描述符,因此它是普通点查找算法中首先要查找的内容。
选项__getattribute__
如果您绝对需要通过__getattribute__
.
- raise
AttributeError
,导致__getattr__
被调用(如果实现)
- 从中返回一些东西
- 用于
super
调用父(可能object
是)实现
- 打电话
__getattr__
- 以某种方式实现自己的点查找算法
例如:
class NoisyAttributes(object):
def __init__(self):
self.test=20
self.test2=21
def __getattribute__(self, name):
print('getting: ' + name)
try:
return super(NoisyAttributes, self).__getattribute__(name)
except AttributeError:
print('oh no, AttributeError caught and reraising')
raise
def __getattr__(self, name):
"""Called if __getattribute__ raises AttributeError"""
return 'close but no ' + name
>>> n = NoisyAttributes()
>>> nfoo = n.foo
getting: foo
oh no, AttributeError caught and reraising
>>> nfoo
'close but no foo'
>>> n.test
getting: test
20
你原本想要的。
这个例子展示了你可以如何做你最初想做的事:
class D(object):
def __init__(self):
self.test=20
self.test2=21
def __getattribute__(self,name):
if name=='test':
return 0.
else:
return super(D, self).__getattribute__(name)
并且会表现得像这样:
>>> o = D()
>>> o.test = 'foo'
>>> o.test
0.0
>>> del o.test
>>> o.test
0.0
>>> del o.test
Traceback (most recent call last):
File "<pyshell#216>", line 1, in <module>
del o.test
AttributeError: test
代码审查
您的代码带有注释。您对 self in 进行了虚线查找__getattribute__
。这就是你得到递归错误的原因。您可以检查 name 是否为"__dict__"
并用于super
解决方法,但这不包括__slots__
. 我将把它作为练习留给读者。
class D(object):
def __init__(self):
self.test=20
self.test2=21
def __getattribute__(self,name):
if name=='test':
return 0.
else: # v--- Dotted lookup on self in __getattribute__
return self.__dict__[name]
>>> print D().test
0.0
>>> print D().test2
...
RuntimeError: maximum recursion depth exceeded in cmp