|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
class Function:
...
def __get__(self, obj, objtype=None):
'''Simulate func_descr_get() in Objects/funcobject.c'''
if obj is None:
return self
return MethodType(self, obj)
怎么确定obj是否为none?
这个 __get__()的触发条件是什么?
@FishC
本帖最后由 isdkz 于 2024-4-11 23:37 编辑
拥有 __get__ 方法的对象会成为描述符,描述符的 __get__ 方法会在 作为类属性被引用的时候触发,
并传入引用的 实例对象作为描述符 __get__ 方法的第二个参数:
当引用对象为类的时候,描述符的__get__方法接收到的第二个参数即obj为None,因为引用对象为类,并没有实例,所以传入None
当引用对象为类的实例的时候,描述符的__get__方法接收到的第二个参数即obj为实例本身
代码举例:
# 定义一个描述符类
class Desc:
def __get__(*args):
print("描述符被引用")
print("传入了参数:", args)
# 定义一个测试类
class Test:
...
# 实例化一个描述符对象
d = Desc()
# 实例化一个测试对象
t = Test()
# 描述符作为对象属性被引用的时候不会触发
t.d = d
print(t.d) # 输出:<__main__.Desc object at 0x000001537CC37C70>
print(Test.d) # 输出:AttributeError: type object 'Test' has no attribute 'd'
del t.d # 删除之前的 t.d
Test.d = d
# 描述符作为类属性被类引用的时候,描述符的__get__方法接收到的第二个参数即obj为None
print(Test.d)
# 输出:
#描述符被引用
#传入了参数: (<__main__.Desc object at 0x000001537CC37C70>, None, <class '__main__.Test'>)
# 描述符作为类属性被实例引用的时候,描述符的__get__方法接收到的第二个参数即obj为实例本身
print(t.d)
# 输出:
#描述符被引用
#传入了参数: (<__main__.Desc object at 0x000001537CC37C70>, <__main__.Test object at 0x000001537CE23E20>, <class '__main__.Test'>)
|
|