【发布时间】:2016-09-10 11:38:25
【问题描述】:
我正在学习 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