python descriptor主要对类的静态属性进行定制化设置,在赋值或者获取值时做一些初始化处理。
一般情况下,对象会优先使用对象属性
class RevealAccess(object):
"""A data descriptor that sets and returns values
normally and prints a message logging their access.
"""
def __init__(self, initval=None, name='var'):
self.val = initval
self.name = name
def __get__(self, obj, objtype):
print 'Retrieving', self.name
return self.val
def __set__(self, obj, val):
print 'Updating' , self.name
self.val = val
class MyClass(object):
x = RevealAccess(10, 'var "x"')
y = 5
if __name__ == '__main__':
m = MyClass()
print m.x
m.x = 20
print m.x
print m.y
n = MyClass()
print n.x
n.x = 30
print n.y
print m.x
输出结果:
Retrieving var "x"
10
Updating var "x"
Retrieving var "x"
20
5
Retrieving var "x"
20
Updating var "x"
5
Retrieving var "x"
30
一般情况下,对象会优先使用对象属性
示例:
class t(object):
a=4
def __init__(self):
self.a = 5
self.b = 8
>>>l = t()
>>>l.__dict__
{'a': 5, 'b': 8}
>>>l.a = 5
如果class t中未定义slef.a,则l.a为4