面向对象-描述符
Posted chrrydot
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面向对象-描述符相关的知识,希望对你有一定的参考价值。
描述符使用
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>
‘‘‘
描述符优先级
- 类属性
- 数据描述符
- 实例属性
- 非数据描述符
- 找不到的属性触发__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
‘‘‘
以上是关于面向对象-描述符的主要内容,如果未能解决你的问题,请参考以下文章
Java面向对象(staticfinal匿名对象内部类包修饰符代码块)