I'm trying to create an object with properties acting like a list. Here is what I mean.
class Unit:
def __init__(self):
self.val = 0
class Bundle:
def __init__(self, N=3):
self.units = [ Unit() for i in range(N) ]
def getvals(self):
return [ unit.val for unit in self.units ]
def setvals(self, vals):
for i, val in enumerate(vals):
self.units[i].val = val
vals = property(getvals, setvals)
Now, this object doesn't behave as expected.
>>> b = Bundle()
>>> b.setvals([1,2,3])
>>> print b.vals, b.getvals()
[1, 2, 3] [1, 2, 3]
>>> b.vals = [4,5,6]
>>> print b.vals, b.getvals()
[4, 5, 6] [1, 2, 3]
So the statements "b.vals = x" and "b.setvals(x)" are not equivalent. Can you tell my why, and how to make it behave properly?
In Python 2, property
only works correctly for new style objects; your Bundle
class must inherit from object
:
class Bundle(object):
...
Once you make that correction, the property works as expected:
>>> b.vals = [4,5,6]
>>> b.vals
[4, 5, 6]
>>> b.getvals()
[4, 5, 6]
>>> [unit.val for unit in b.units]
[4, 5, 6]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With