Python 通过对象调用描述符;行不通

Python 通过对象调用描述符;行不通,python,descriptor,getattribute,python-3.9,Python,Descriptor,Getattribute,Python 3.9,简言之,我有以下资料: class Descriptor: def __set_name__(self, owner, name): self.public_name = name self.private_name = '_' + name def __get__(self, instance, owner): print('something') def __set__(self, instance, value):

简言之,我有以下资料:

class Descriptor:
    def __set_name__(self, owner, name):
        self.public_name = name
        self.private_name = '_' + name

    def __get__(self, instance, owner):
        print('something')

    def __set__(self, instance, value):
        setattr(instance, self.private_name, value)

class C:
    arg1 = Descriptor()

    def __init__(self, name):
        self.arg1 = name

    def __getattribute__(self, attr):
        if attr == 'arg1':
            object.__getattribute__(type(self), attr)

c = C('Henry')
c.arg1
为什么
c.arg1
什么都不做,而不打印出
中定义的
内容

显然,如果我将
\uuuu getattribute\uuuu
中的代码更改为以下选项:

  • type(self).arg1
  • object.\uuuuu getattribute\uuuuu(self,attr)
它会像往常一样工作

此外,以下方法也有效:

  • getattr(C,'arg1')

但当我将它设置为
对象时就不是了。我想知道为什么它不起作用。

对象。\uuuuu getattribute\uuuu
是错误的
\uuu getattribute\uuuuu
方法,用于查找类型的属性<代码>类型。\uuuu getattribute\uuuu
是正确的方法

如果对类型调用
object.\uuuu getattribute\uuu
,它将对普通对象执行属性查找过程。它不会搜索参数的MRO,也不会调用描述符,除非在元类上找到它们


(也就是说,即使您切换到调用
type.\uuuu getattribute.\uuuuu
,您的
\uuu getattribute.\uuuuuu
实现也没有意义。它会打印您希望打印的内容,但没有意义。)

为什么要传递
type(self)
而不是
self
?(为什么要实现
\uuuuu getattribute\uuuuu
?至少有三个原因,
\uuuu getattribute\uuuuuu
没有意义。)@user2357112supportsMonica我正在学习描述符的一般工作方式,所以要测试所有可能的情况。我一直在使用
对象。\uuuu getattribute\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu(type(self),attr)
case。另外,在实现
\uuuuuuuuu getattr\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。您的将始终返回
None
。类似于描述符的
\uuuu get\uuuu
。返回带有副作用的
None
会让人很难理解和调试。@schwobasegll我完全知道这一点,但是
\uu get\uuu
甚至不起作用。因此,进一步扩展它是有意义的。如果要返回某个对象,例如
返回对象。\uuuu getattribute\uuuu(type(self),attr)
您会意识到在类上访问时,会返回描述符对象。感谢您的解释。