是否有像 getattr/hasattr 这样的函数绕过实例属性?

问题描述

标准库中是否有类似内置函数 getattrhasattr 但在属性查找过程中绕过实例属性函数,例如 {{3} }?

让我们称这些假设函数getclassattrhasclassattr。以下是我期望的实现:

null = object()

def getclassattr(obj,name,default=null,/):
    if not isinstance(name,str):
        raise TypeError('getclassattr(): attribute name must be string')
    try:
        classmro = vars(type)['__mro__'].__get__(type(obj))
        for cls in classmro:
            classdict = vars(type)['__dict__'].__get__(cls)
            if name in classdict:
                attr = classdict[name]
                attrclassmro = vars(type)['__mro__'].__get__(type(attr))
                for attrclass in attrclassmro:
                    attrclassdict = vars(type)['__dict__'].__get__(attrclass)
                    if '__get__' in attrclassdict:
                        return attrclassdict['__get__'](attr,obj,type(obj))
                return attr
        classname = vars(type)['__name__'].__get__(type(obj))
        raise AttributeError(f'{classname!r} object has no attribute {name!r}')
    except AttributeError as exc:
        try:
            classmro = vars(type)['__mro__'].__get__(type(obj))
            for cls in classmro:
                classdict = vars(type)['__dict__'].__get__(cls)
                if '__getattr__' in classdict:
                    return classdict['__getattr__'](obj,name)
        except AttributeError as exc_2:
            exc = exc_2
        except BaseException as exc_2:
            raise exc_2 from None
        if default is not null:
            return default
        raise exc from None
def hasclassattr(obj,/):
    try:
        getclassattr(obj,name)
    except AttributeError:
        return False
    return True

用例是内置类 implicit lookup of special methods:* 的纯 Python 实现

import types

class ClassMethod:

    def __init__(self,function):
        self.__func__ = function

    def __get__(self,instance,owner=None):
        if instance is None and owner is None:
            raise TypeError('__get__(None,None) is invalid')
        if owner is None:
            owner = type(instance)
        # NOT hasattr.
        if hasclassattr(self.__func__,'__get__'):
            # NOT getattr.
            return getclassattr(self.__func__,'__get__')(owner,type(owner))
        return types.MethodType(self.__func__,owner)

    @property
    def __isabstractmethod__(self):
        return hasattr(self.__func__,'__isabstractmethod__')

* 请注意,此实现不适用于内置函数 getattrhasattr,因为它们首先在实例属性中查找,作为与内置类 {{1} 的比较} 显示

classmethod

解决方法

不是像 implicit lookup of special methods 那样引入新函数 getclassattrhasclassattr 在属性查找期间绕过实例属性,另一种方法是引入代理类(我们称之为 { {1}}) 覆盖了方法 bypass。我认为这可能是一个更好的方法,因为方法 __getattribute__ 是一个为自定义属性查找而设计的钩子,它与内置函数 __getattribute__getattr 一起工作,但也与属性一起工作检索运算符hasattr

.