Python中__get__描述符的用法与原理详解
“”""
https://www.jb51.net/article/86749.htm
https://python3-cookbook.readthedocs.io/zh_CN/latest/c08/p09_create_new_kind_of_class_or_instance_attribute.html
“”"
class C(object):
“”"
存在了__get__的方法的类称之为描述符类
descriptor 的实例自己访问自己是不会触发__get__,而会触发__call__,只有 descriptor 作为其它类的属性的时候才会触发 __get___
"""
a = 'abc'
def __get__(self, instance, owner):
print("__get__() is called", instance, owner)
return self
class C2(object):
# 为了使用一个描述器,需将这个描述器的实例作为类属性放到一个类的定义中.
d = C() # descriptor 的实例自己访问自己是不会触发__get__,而会触发__call__,只有 descriptor 作为其它类的属性的时候才会触发 get_
if name == ‘main’:
# 不触发
c = C()
print(c.a)
# 触发
c2 = C2()
print(c2.d.a)
Python中__get__描述符的用法与原理详解
1 回复
# __get__描述符的核心示例
class Descriptor:
"""基础描述符类"""
def __get__(self, instance, owner):
print(f"__get__被调用: instance={instance}, owner={owner}")
return "描述符返回值"
def __set__(self, instance, value):
print(f"__set__被调用: instance={instance}, value={value}")
instance._value = value
class MyClass:
attr = Descriptor() # 类属性是描述符实例
def __init__(self):
self._value = None
# 使用示例
obj = MyClass()
print(obj.attr) # 触发__get__
obj.attr = 42 # 触发__set__
描述符就是实现了__get__、__set__或__delete__方法的类。当通过实例访问描述符属性时,Python会自动调用这些方法。
核心原理:
__get__(self, instance, owner):instance是访问属性的实例,owner是拥有该属性的类- 属性查找顺序:
instance.__dict__→类.__dict__→ 父类链 - 如果在类中找到的是描述符对象,就调用它的
__get__方法
典型应用场景:
@property装饰器底层就是描述符- Django的模型字段
- 数据验证和类型检查
关键点:
- 描述符必须定义为类属性
__get__在通过实例访问时触发__get__在通过类访问时也会触发,此时instance为None
一句话总结:描述符让你能自定义属性访问的底层行为。

