> I have a class that contains a list of items
> I can set items using __setitem__ but if i want to set the while list, i
> changes the variable from a myclass to a list. How can i accomblish this
> Example
>>>> C = myclass()
>>>> C[0] = 57
>>>> type(C)
> myclass
>>>> C = [57,58,59,60]
This creates a list, and binds the name that used to refer to the
myclass to now refer to the list. The myclass object will go away,
since there are no more refs to it.
>>>> type(C)
> list
Why is that a surprise?
As for how to add multiple items to the existing mylist, how about:
for index, item in enumerate([57, 50, 59, 60]) :
C[index] = item
Alternatively, you could call one of the other methods in the class. But since you gave us no clues, I'm shouldn't guess what it was called. But if I were to make such a class, I might use slicing:
C[:] = [57, 50, 59, 60]
BTW, your naming capitalization is backwards. Class names should begin
with a capital, Myclass. Instances should begin with lowercase -
myinstance
> Alternatively, you could call one of the other methods in the class.
> But since you gave us no clues, I'm shouldn't guess what it was called.
> But if I were to make such a class, I might use slicing:
> C[:] = [57, 50, 59, 60]
In 3.x, you would write __setitem__ to recognize that the 'key' is a slice object rather than an int and act accordingly. (In 2.x, you would write __setslice__.) Actually, if you write
def __setitem__(self, key, value):
self.somelist[key] = value
as you might have done already, you get slice getting, setting, and deleting for free. Try Dave's line in your code.
Kevin Anthony wrote:
> I'm not supprised... and understand why it's happening. I'm asking how > to get around it.
I don't think you do understand what's happening.
What's happening is the basic application of name binding in Python:
--> C = anything
whatever C was bound to before, it no longer is, because now it is bound to <anything>.
What you are trying to do is mutate C, not rebind it. As Dave suggested, you can use slice notation ([:]) or some method of C (that you create) to do so.
> Basically i'm asking how to override, if i can, the `=`
Terry Reedy wrote:
> In 3.x, you would write __setitem__ to recognize that the 'key' is a > slice object rather than an int and act accordingly. (In 2.x, you would > write __setslice__.)
I'm not sure how far back it goes, but at least from 2.4 forward __setitem__ works with slices just fine.
Ethan Furman wrote:
> Terry Reedy wrote:
>> In 3.x, you would write __setitem__ to recognize that the 'key' is a
>> slice object rather than an int and act accordingly. (In 2.x, you would
>> write __setslice__.)
> I'm not sure how far back it goes, but at least from 2.4 forward
> __setitem__ works with slices just fine.
The __...slice__() methods are deprecated since 2.0.