描述符使用
Foo接管了Bar的x值,当x值被操作的时候都调用Foo相应的get/set/delete操作
class Foo:
def __get__(self,instance,owner):
print('===>get',instance,owner)
def __set__(self,instance,value):
print('===>set',instance,value)
def __delete__(self, instance):
print('===>delete',instance)
class Bar:
x = Foo()
def __init__(self,n):
self.x = n
b1 = Bar(10)
print(b1.__dict__)
print(Bar.__dict__)
print(b1.x)
'''
===>set <__main__.Bar object at 0x0000022A4A214D68> 10
{}
{'__module__': '__main__', 'x': <__main__.Foo object at 0x0000022A4A214C50>, '__init__': <function Bar.__init__ at 0x0000022A4A1F6C80>, '__dict__': <attribute '__dict__' of 'Bar' objects>, '__weakref__': <attribute '__weakref__' of 'Bar' objects>, '__doc__': None}
===>get <__main__.Bar object at 0x0000022A4A214D68> <class '__main__.Bar'>
None
'''
class Foo:
def __get__(self,instance,owner):
print('===>get',instance,owner)
def __set__(self,instance,value):
print('===>set',instance,value)
def __delete__(self, instance):
print('===>delete',instance)
class Bar:
x = Foo()
def __init__(self,n):
self.x = n
# print(Bar.x)
# Bar.x = 1 #不触发描述符,因为类属性优先级更高,如果不注释,后面的语句也不触发描述符
b1 = Bar(10)
print(b1.x)
del b1.x
'''
===>set <__main__.Bar object at 0x000001D368C14CF8> 10
===>get <__main__.Bar object at 0x000001D368C14CF8> <class '__main__.Bar'>
None
===>delete <__main__.Bar object at 0x000001D368C14CF8>
'''
描述符优先级
- 类属性
- 数据描述符---》至少实现了get、set方法
- 实例属性
- 非数据描述符 ----》没有set方法
- 找不到的属性触发__getattr__()
class Foo:
def __get__(self,instance,owner):
print('===>get',instance,owner)
def __set__(self,instance,value):
print('===>set',instance,value)
def __delete__(self, instance):
print('===>delete',instance)
class Bar:
x = Foo()
def __init__(self,n):
self.x = n
# print(Bar.x)
Bar.x = 1 #不触发描述符,因为类属性优先级更高
'''
Process finished with exit code 0
'''