Python 数据描述符不能用作实例变量? [英] Python data descriptor did not work as instance variable?

查看:43
本文介绍了Python 数据描述符不能用作实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如官方演示所描述的这里,以下代码将打印 Retrieving var "x".

As the official demo described here, the following code will print Retrieving var "x".

class RevealAccess(object):
    """A data descriptor that sets and returns values
       normally and prints a message logging their access.
    """

    def __init__(self, initval=None, name='var'):
        self.val = initval
        self.name = name

    def __get__(self, obj, objtype):
        print 'Retrieving', self.name
        return self.val

    def __set__(self, obj, val):
        print 'Updating', self.name
        self.val = val


class MyClass1(object):
    x = RevealAccess(10, 'var "x"')

MyClass1().x

但是如果 x 是一个实例变量,数据描述符机制将无法工作,下面的代码将不会打印任何内容.

But if x is an instance variable, the data descriptor machinery will not work, the following code will not print anything.

class MyClass2(object):
    def __init__(self):
       self.x = RevealAccess(10, 'var "x"')

MyClass2().x

而且,如果我按照此处所述手动实现数据描述符机制,下面的代码将再次Retrieving var "x".

And, if I implements the data descriptor machinery manually as described here, the following code will Retrieving var "x" again.

class MyClass3(object):
    def __init__(self):
       self.x = RevealAccess(10, 'var "x"')

    def __getattribute__(self, key):
        "Emulate type_getattro() in Objects/typeobject.c"
        v = object.__getattribute__(self, key)
        if hasattr(v, '__get__'):
            return v.__get__(None, self)
        return v

MyClass3().x

那么,默认的数据描述符机制是否没有按照文档描述的那样实现?

So, is the default data descriptor machinery not implemented as the doc described?

我使用的是 python 2.7.10.

I am using python 2.7.10.

推荐答案

这里的描述方法是错误的.Python 数据模型有正确的描述:

The descriptor how-to is wrong here. The Python data model has the correct description:

以下方法 [__get__, __set__, and __delete__] 仅适用于类的实例包含方法(所谓的描述符类)出现在所有者类(描述符必须在所有者的类中字典或在其父母之一的类字典中).

The following methods [__get__, __set__, and __delete__] only apply when an instance of the class containing the method (a so-called descriptor class) appears in an owner class (the descriptor must be in either the owner’s class dictionary or in the class dictionary for one of its parents).

描述符必须是类属性.

这篇关于Python 数据描述符不能用作实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆