python - 关于 python 描述符的几个说明

标签 python

Descriptors HowTo

有人可以通过示例帮助我理解这一点吗?

如果实例的字典中有一个条目与数据描述符同名,则数据描述符优先。如果一个实例的字典有一个与非数据描述符同名的条目,则该字典条目优先。

该实现通过优先链工作,该优先链使数据描述符优先于实例变量,实例变量优先于非数据描述符,并将最低优先级分配给 _ getattr_()(如果提供)。

具体我不明白的是:

  1. 一个实例的字典怎么会有一个与描述符同名的条目。能举个例子吗?

  2. 您还可以给我一个例子,其中数据描述符优先于实例变量,实例变量优先于非数据描述符等吗?

同样在下面的代码中,我惊讶地看到测试类中的 self.x 调用了 __ set __: 我相信这种行为是因为上面链接中的解释:

对于对象,机制在 object.__ getattribute __ () 中,它将 b.x 转换为 type(b)。 __ 字典 __ ['x']。 __ 得到 __(b,类型(b))。对吧??

    #! /usr/bin/env python
    class descclass(object):

            def __init__(self, value):
                    print "in desc init"
                    self.value = value
                    print "out of desc init"                

            def __get__(self, inst, insttype):
                    print "in desc get"
                    return self.value

            def __set__(self,inst, val):
                    print "in desc set"
                    self.value = val

    class testclass(object):

            x = descclass(100)
            print "desc created"

            def __init__(self, val):
                    print "in testclass init"
                    self.x = val  # this invokes __set__ on descriptor in x
                    print "out of testclass init"

    if __name__ == '__main__':

            t = testclass(45)
            print t.x
            print vars(t)
            print vars(testclass)

最佳答案

这是一个例子。

# Not a data descriptor because it doesn't define __set__
class NonDataDescriptor(object):
    def __get__(self, obj, objtype):
        return 3

class Namespace(object):

    # Data descriptor - defines both __get__ and __set__
    @property
    def foo(self):
        return 3

    bar = NonDataDescriptor()

x = Namespace()
x.__dict__['foo'] = 4  # We bypass the foo descriptor's __set__ here,
x.bar = 4              # but there's no bar setter, so this one goes to the dict

# x now has foo and bar descriptors and __dict__ entries

print x.foo  # prints 3 - data descriptor wins over instance __dict__ entry
print x.bar  # prints 4 - instance __dict__ entry wins over non-data descriptor

关于python - 关于 python 描述符的几个说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18368019/

相关文章:

python - 解包值过多时出现错误(预期2)

python - 尝试在 Tensorflow 中使用未初始化的值变量(使用了 sess.run(tf.global_variables_initializer()) !)

Python - 将月、日、年组合成日期列

相当于 ~/.bashrc 的 Python

python - 无法在 Dropbox 文件夹中执行 heroku 的 Python 教程

Python - 捕获无人机程序的任何错误

python - 以编程方式编辑 pyqt4 python 中的选项卡顺序

python - 从文本文件中解析唯一的单词

python - 更改行数据以防它与不同的行不匹配

python - 我将如何解决此 Python 代码中的 'list index out of range' 错误?