Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 访问描述符实例_Python_Python 3.x - Fatal编程技术网

Python 访问描述符实例

Python 访问描述符实例,python,python-3.x,Python,Python 3.x,当定义描述符值时,将重写检索等,从而使描述符的实例实际上不可访问 也就是说,不能使用描述符\u attr.descriptor\u attr写入实例\u。描述符上的某些\u方法\u。。。不行。我的问题基本上是如何仍然可以访问描述符的实例…您需要转到类本身: type(instance_with_descriptor_attr).descriptor_attr 演示: >>> class Foo(): ... @property ... def bar(self

当定义描述符值时,将重写检索等,从而使描述符的实例实际上不可访问


也就是说,不能使用描述符\u attr.descriptor\u attr写入实例\u。描述符上的某些\u方法\u。。。不行。我的问题基本上是如何仍然可以访问描述符的实例…

您需要转到类本身:

type(instance_with_descriptor_attr).descriptor_attr
演示:

>>> class Foo():
...     @property
...     def bar(self): return 'bar'
... 
>>> foo = Foo()
>>> foo.bar
'bar'
>>> type(foo).bar
<property object at 0x109f24310>

正如eryksun所指出的,Martijn的解决方案适用于属性,但并非所有描述符:

class Desc(object):
    def __init__(self, val=None):
        self.val = val

    def __get__(self, obj, cls):
        return self.val

    def __set__(self, obj, val):
        self.val = val

class Test(object):
    x = Desc(5)

>>> o = Test()
>>> print o.x
5
>>> print Test.x
5
它适用于属性描述符的原因可以在文档中的示例属性描述符实现中看到:

关键是_get _函数:

def __get__(self, obj, objtype=None):
    if obj is None:
        return self
    if self.fget is None:
        raise AttributeError, "unreadable attribute"
    return self.fget(obj)
如果obj为None,则返回self,self是描述符本身的实例。obj是访问描述符的类的实例。从类实例访问属性时,obj是该实例;从类对象访问属性时,obj是无

将上一个描述符更改为:

class Desc(object):
    def __init__(self, val=None):
        self.val = val

    def __get__(self, obj, cls):
        if obj is None:
            return self
        return self.val

    def __set__(self, obj, val):
        self.val = val

class Test(object):
    x = Desc(5)
如果您使用的是python shell,则必须重新定义类

o = Test()
>>> print o.x
5
>>> print Test.x
<__main__.Desc object at 0x23205d0>
这适用于属性,但数据描述符通常在通过类访问时可能不会返回自身,因此需要搜索类的dict及其基。