M
mrkafk
Hello everyone,
I'm trying to do seemingly trivial thing with descriptors: have
another attribute updated on dot access in object defined using
descriptors.
For example, let's take a simple example where you set an attribute s
to a string and have another attribute l set automatically to its
length.
def __init__(self,val):
self.s=val
self.l=len(val)
print "creating value: ", self.s
print "id(self.l)", id(self.l)
def __set__(self, obj, val):
self.s=val
self.l=len(val)
print "setting value:", self.s, "length:", self.l
def __get__(self, obj, type=None):
print "getting value:", self.s, "length:", self.l
return self.l
m=Desc('abc')
l=m.l
creating value: abc
id(self.l) 10049688setting value: test string length: 11
However, the attribute ta.l didn't get updated:
3
This is so much weirder that object id of ta.l is the same as id of
instance of descriptor:
10049688
A setter function should have updated self.l just like it updated
self.s:
def __set__(self, obj, val):
self.s=val
self.l=len(val)
print "setting value:", self.s, "length:", self.l
Yet it didn't happen.
automatically: say, in class of Squares I get area automatically
updated on updating side, etc.
Yet, I'm struggling with getting it done in Python. Descriptors are a
great idea, but I would like to see them implemented in Python in a
way that makes it easier to get desireable side effects.
I'm trying to do seemingly trivial thing with descriptors: have
another attribute updated on dot access in object defined using
descriptors.
For example, let's take a simple example where you set an attribute s
to a string and have another attribute l set automatically to its
length.
def __init__(self,val):
self.s=val
self.l=len(val)
print "creating value: ", self.s
print "id(self.l)", id(self.l)
def __set__(self, obj, val):
self.s=val
self.l=len(val)
print "setting value:", self.s, "length:", self.l
def __get__(self, obj, type=None):
print "getting value:", self.s, "length:", self.l
return self.l
m=Desc('abc')
l=m.l
creating value: abc
id(self.l) 10049688setting value: test string length: 11
However, the attribute ta.l didn't get updated:
3
This is so much weirder that object id of ta.l is the same as id of
instance of descriptor:
10049688
A setter function should have updated self.l just like it updated
self.s:
def __set__(self, obj, val):
self.s=val
self.l=len(val)
print "setting value:", self.s, "length:", self.l
Yet it didn't happen.
on dot access (getting/setting) I can get other attributes updatedFrom my POV, the main benefit of a descriptor lies in its side effect:
automatically: say, in class of Squares I get area automatically
updated on updating side, etc.
Yet, I'm struggling with getting it done in Python. Descriptors are a
great idea, but I would like to see them implemented in Python in a
way that makes it easier to get desireable side effects.