您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

为什么在定义为实例属性时未调用描述符?

为什么在定义为实例属性时未调用描述符?

这是因为描述符仅应定义为类属性,而不是实例属性

文档

以下方法仅在包含该方法的类的实例(所谓的描述符类)出现在所有者类中( )时适用。

为了使描述符也能与实例属性一起使用,您需要重写。__getattribute__方法BusinessLogic(尚未进行全面测试,但可以根据情况工作):

def __getattribute__(self, attr):
        obj = object.__getattribute__(self, attr)
        if hasattr(obj, '__get__'):
            return obj.__get__(self, type(self))
        return obj

如果您有数据描述符,则还需要处理该__setattr__零件。

def __setattr__(self, attr, val):
    try:
        obj = object.__getattribute__(self, attr)
    except AttributeError:
        # This will be raised if we are setting the attribute for the first time
        # i.e inside `__init__` in your case.
        object.__setattr__(self, attr, val)
    else:
        if hasattr(obj, '__set__'):
            obj.__set__(self, val)
        else:
            object.__setattr__(self, attr, val)
其他 2022/1/1 18:48:12 有492人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶