编写非数据描述符

问题描述 投票:4回答:1

我正在学习python中的描述符。我想编写一个非数据描述符,但是将描述符作为其类方法的类在调用类方法时不会调用__get__特殊方法。这是我的示例(没有__set__):

class D(object):

    "The Descriptor"

    def __init__(self, x = 1395):
        self.x = x

    def __get__(self, instance, owner):
        print "getting", self.x
        return self.x


class C(object):

    d = D()

    def __init__(self, d):
        self.d = d

这是我的称呼:

>>> c = C(4)
>>> c.d
4

描述符类的__get__没有任何调用。但是当我还设置了__set__时,描述符似乎已激活:

class D(object):

"The Descriptor"

    def __init__(self, x = 1395):
        self.x = x

    def __get__(self, instance, owner):
        print "getting", self.x
        return self.x

    def __set__(self, instance, value):
        print "setting", self.x
        self.x = value

class C(object):

    d = D()

    def __init__(self, d):
        self.d = d

现在我创建一个C实例:

>>> c=C(4)
setting 1395
>>> c.d
getting 4
4

__get__, __set__都存在。似乎我缺少关于描述符及其使用方式的一些基本概念。谁能解释__get__, __set__的这种行为?

python python-2.7 descriptor python-descriptors
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.