Home > Back-end >  How to change a list item with class function?
How to change a list item with class function?

Time:01-03

I want to change the content of a List with a class funcion. The class takes an item from the list as a parameter. Now I want to change this item in the list.

How do I do that? I was only able to change the parameter in the instance but not the original list.

list = ["just", "an", "list"]

class Test():
   def __init__(self, bla):
        self.bla = bla

    def blupp(self):
        self.bla = "a"

test = Test(list[1])

If I run test.blupp() I want the list to be ["just", "a", "list"]

Thanks! (I hope nothing important is missing. This is my first question here)

CodePudding user response:

list[1] is an expression that evaluates to "an" before Test is ever called. You have to pass the list and the index to modify separately, and let blupp make the assignment.

class Test:
    def __init__(self, bla, x):
        self.bla = bla
        self.x = x

    def blupp(self):
        self.bla[self.x] = "a"


test = Test(list, 1)

Or, store a function that makes the assignment in the instance of Test:

class test:
    def __init__(self, f):
        self.f = f

    def blupp(self):
        self.f("a")

test = Test(lambda x: list.__setitem__(1, x))

CodePudding user response:

From what I understand, you are asking to change "an" to "a" in the list ["just", "an", "list"] by calling a method called blupp. To achieve this we need to redefine list[1]

# Define The List

list = ["just", "an", "list"]

class Test:
    def __init__(self, bla):
        self.bla = bla

    def blupp(self):
        # Choose what to redefine 'an' with
        self.new_bla = "a"

        # Get the position of self.bla 
        list[list.index(self.bla)] = self.new_bla # Replace 'an' with 'a'
        print(list)

# Define the test object
test = Test(list[1])

# Call the blupp() method
test.blupp()

And we get an output of:

["just", "a", "list"]
  • Related