Stack Overflow Asked by Vinicius Miki on December 16, 2021
Dears,
I am trying to understand better the OOP paradigm in Python, so I’ve created this simple class
class MyList:
def __init__(self,list):
self.list=list
list1=MyList([1,2,3,4,5])
Until here is everything fine, the problem occurs when I try to set a value to any element of my list. As example:
list1[0]=5
Then I got this TypeError: ‘MyList’ object does not support item assignment
Someone could help me with this?
I got it! I implemented the special method setitem and getitem and it worked. Thank you all
class MyList:
def __init__(self,list):
self.list=list
def __getitem__(self, index):
return self.list[index]
def __setitem__(self, index, value):
self.list[index] = value
Answered by Vinicius Miki on December 16, 2021
You are probably trying to create a new MyList type which should have the functionalities of a normal Python list plus some functionalities you might like to add or modify. For this to work, you need to inherit from the inbuilt Python list
class, like so,
class MyList(list):
pass
list1=MyList([1,2,3,4,5])
list1[0]=5
Now in your MyList
class, define only those methods which you want to change in the inbuilt list
class
Answered by Prashant Sethi on December 16, 2021
Since you're trying to better understand OOP, here's something you can try: Subclass list
itself, so your class gets all the properties that list
s do.
class MyList(list):
def __init__(self,list):
super().__init__(list)
list1 = MyList([1,2,3,4,5])
list1[0] = 5
print(list1)
# [5, 2, 3, 4, 5]
Answered by M Z on December 16, 2021
class MyList:
def __init__(self,list):
self.list=list
def __str__(self):
return str(self.__dict__)
list1=MyList([1,2,3,4,5])
print(list1)
list1.list[0]=5
print(list1)
You need to assign to the list attribute not to the class
Answered by Aparna on December 16, 2021
You don't have any code in the class that allows for item assignment. For an object to allow item assignment, it needs to implement __setitem__
.
You would need something like:
class MyList:
def __init__(self,list):
self.list=list
def __setitem__(self, i, elem):
self.list[i] = elem
Answered by Carcigenicate on December 16, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP