- 论坛徽章:
- 0
|
>>> class NonDataDes (object):
def __get__(self, obj, type=None):
print 'NonDataDes: Access...Ignore'
>>> class DataDes (object):
def __get__(self, obj, type=None):
print 'DataDes: Access...Ignore'
def __set__(self, obj, val):
print 'DataDes: Assign...Ignore'
>>> class Test (object):
nondata = NonDataDes()
data = DataDes()
foo = 0
>>> a = Test()
>>> a.data
DataDes: Access...Ignore
>>> a.data = 1
DataDes: Assign...Ignore
>>> a.__dict__['data'] = 2
>>> a.data
DataDes: Access...Ignore
>>> type(a).data = 3
>>> a.data
2
>>> type(a).data
3
>>> a.nondata
NonDataDes: Access...Ignore
>>> a.nondata = 4
>>> a.nondata
4
>>> a.foo
0
>>> a.foo = 5
>>> a.foo
5
>>>
|
上边的代码先验证了一个关于__getattribute__的Precedence 的描述,具体描述如下:
***引自"Core Python Programming, Second Edition, Wesley J. Chun"
The way __getattribute__() works needs to be covered, as it was implemented to behave in a very specific way. Thus it is very important to recognize this ordering:
- Class attributes
- Data descriptors
- Instance attributes
- Non-data descriptors
- Defaulting to __getattr__()
A descriptor is a class attribute, so all class attributes have the highest priority. You can even replace a descriptor by simply reassigning its original reference to other objects. They are followed closely behind by descriptors with __get__() and __set__() implemented. If you have an agent, it will do all your work for you!
Otherwise, it should just default to the local object's __dict__, meaning that it will be an instance attribute. The non-data descriptors come next. This may sound surprising because on first glance, one would think that these should be higher up in the food chain than instance attributes, but that is not the case. The purpose of non-data descriptors is only to provide a value if one is not already part of an instance, sort of how __getattr__() is only called if an attribute cannot be found in an instance's __dict__!
Speaking of __getattr__(), if no non-data descriptor is found, then __getattribute__() raises an AttributeError, and that in turn causes __getattr__() to be invoked as the last stand before AttributeError is raised to the user.
|
问题是这样的:
Python中这样一个性质
foo是class Test的一个Class Attribute.
a是class Test的一个Instance.
当通过a.foo对foo赋值时,会生成一个同名的Instance Attribute。
之后通过a.foo访问foo的内容的时候,会返回名为foo的Instance Attribute的内容。
这样看起来是Instance Attribute的优先级要高于Class Attribute,和前面Precedence的描述不统一???
希望哪位大大解释一下?
[ 本帖最后由 conjurator 于 2009-6-7 20:17 编辑 ] |
|