I am learning about descriptors in python. I want to write a non-data descriptor but the class having the descriptor as its classmethod doesn't call the __get__
special method when I call the classmethod. This is my example (without the __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
And here is how I call it:
>>> c = C(4)
>>> c.d
4
The __get__
of the descriptor class gets no call. But when I also set a __set__
the descriptor seems to get activated:
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
Now I create a C
instance:
>>> c=C(4)
setting 1395
>>> c.d
getting 4
4
and both of __get__, __set__
are present. It seems that I am missing some basic concepts about descriptors and how they can be used. Can anyone explain this behaviour of __get__, __set__
?
__set__
is defined. what is this? – Gametangium