Python覆盖__getattr__用于嵌套赋值,但不用于引用?

sla*_*acy 0 python

这是我正在寻找的行为:

>>> o = SomeClass()
>>> # Works: 
>>> o.foo.bar = 'bar' 
>>> print o.foo.bar
'bar'
>>> # The in-between object would be of type SomeClass as well:
>>> print o.foo 
>>> <__main__.SomeClass object at 0x7fea2f0ef810>

>>> # I want referencing an unassigned attribute to fail: 
>>> print o.baz
Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
    print o.baz
AttributeError: 'SomeClass' object has no attribute 'baz'
Run Code Online (Sandbox Code Playgroud)

换句话说,我想以这样的方式覆盖__getattr____setattr__(并且可能__getattribute__)以类似于defaultdict的方式工作,允许赋值给任意属性,但是如果一个属性刚被引用但未被赋值,则它会抛出一个AttributeError,因为它通常会.

这可能吗?

Gle*_*ard 6

这在Python中是不可能的.

你问的是这个:

>>> o = SomeClass()
>>> o.foo.bar = 'bar' 
>>> print o.foo.bar
'bar'
>>> a = o.baz
raises AttributeError
Run Code Online (Sandbox Code Playgroud)

这是不可能做到的.没有办法区分

>>> o.foo.bar = 'bar' 
Run Code Online (Sandbox Code Playgroud)

>>> temp = o.foo
>>> temp.bar = 'bar' 
Run Code Online (Sandbox Code Playgroud)

它们在逻辑上是等价的,并且在两种情况下Python都在做同样的事情.您不能区分它们以便在后一种情况下引发异常而不是前者.