Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python propery: list-like object

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?

like image 370
Antonius Avatar asked Jan 15 '23 21:01

Antonius


1 Answers

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]
like image 65
Martijn Pieters Avatar answered Jan 23 '23 01:01

Martijn Pieters