Home > OS >  Add a list into an object from a class Python
Add a list into an object from a class Python

Time:01-26

I have a class in Python 3.8

       class SomeClass:
            data=[]
            def __init__(self,my_list=[]):     
            for v in my_list:
                SomeClass.data.append(v)       

Once an object is created from a list o lists like this:

       # The object always will be a list or a list of lists
       first_object= [['abc', 17.67, 1.5],['ijk', 9.68, 2.3],['efg', 50.3, 3.8],['xyz', 25.5, 16.2]]

I need that after an object is created, add a new list to the previous object and create a new one. The class should also have an option to add single lists into the object like this:

      second_object = first_object   ['wmk', 79, 2.3]

When i'm trying to do this i get this error:

      TypeError: unsupported operand type(s) for  : 'SomeClass' and 'list'

How can I fix this?, thanks in advance

CodePudding user response:

you should add to the class a __add__ function, so you can add an object to that class to do something, in this case i raised a TypeError if it wasn't list but you can do whatever you want

Code:

class SomeClass():
   def __init__(self,list1):
       self.data = list1
   def __add__(self,obj):
       if isinstance(obj,list):
           return self.data obj
       else:
           raise TypeError("It is not a list!!")

so you can do:

classinstance = SomeClass([1,2,3,4])
classinstance =[10,20,30,40,50,60,70,80]
print(classinstance)

output:

[1, 2, 3, 4, 10, 20, 30, 40, 50, 60, 70, 80]

CodePudding user response:

The class SomeClass is just a blueprint for how data should be stored and processed. You need to create what's called an instance of the class where you fill the class in with actual data.

class SomeClass:
    def __init__(self,my_list=[]):
        self.data=[]     
        for v in my_list:
            self.data.append(v)   

first_object = SomeClass([['abc', 17.67, 1.5],['ijk', 9.68, 2.3],['efg', 50.3, 3.8],['xyz', 25.5, 16.2]])
second_object = SomeClass(first_object.data   ['wmk', 79, 2.3])
  •  Tags:  
  • Related