Home > Software design >  How to alter a variable via a dictionary?
How to alter a variable via a dictionary?

Time:10-20

How would you go about changing a variables value using a dictionary?

class Solution(object):
  def __init__(self):
    self.slot1 = ""
    self.slot2 = ""
    self.slot3 = ""
    self.slot4 = ""
    self.slot5 = ""
    self.slotDictionary = {1: self.slot1, 2: self.slot2, 3: self.slot3, 4: self.slot4, 5: self.slot5}
  def checkAnswer(self):
    choice = int(input("What is the answer?"))
    self.slotDictionary[choice] = "something"
solution = Solution()
solution.checkAnswer()

However when running this it does not change the value of the self variables. How would i go about this?

CodePudding user response:

Even though it is logically not possible but there is hack you may use. And it's by using list. If you wrap str with a list then it can be achieved.

Check the code below:

class Solution(object):
  def __init__(self):
    self.slot1 = [""]
    self.slot2 = [""]
    self.slot3 = [""]
    self.slot4 = [""]
    self.slot5 = [""]
    self.slotDictionary = {1: self.slot1, 2: self.slot2, 3: self.slot3, 4: self.slot4, 5: self.slot5}
  def checkAnswer(self):
    choice = int(input("What is the answer?"))
    self.slotDictionary[choice][0] = "something"
solution = Solution()
solution.checkAnswer()

CodePudding user response:

You can't change an immutable object (like str). You have initialized your attribute with an immutable object so, python will always create a new object in order to modify the value (the reference will be different between the one store in the attribut and the one store in your dictionary after modifying your attribute). If you use a mutable type, like list, dict or a specific class, you will be able, in this case, to modify the object you want.

Note: there is many other approach to deal with your problem. Passing your attribut through other attribut of the class is not a common use case and maybe a wrong materialization of the problem. If your purpose is to make a choice on your attributs list "self.dict" with "getattr" may help you.

CodePudding user response:

You can change class variables by their string (name) with setattr().

class Solution(object):
  def __init__(self):
    self.slot1 = ""
    self.slot2 = ""
    self.slot3 = ""
    self.slot4 = ""
    self.slot5 = ""
    self.slotDictionary = {1: 'slot1', 2: 'slot2', 3: 'slot3', 4: 'slot4', 5: 'slot5'}
  def checkAnswer(self):
    choice = int(input("What is the answer?"))
    setattr(self, self.slotDictionary[choice], "something")
solution = Solution()
solution.checkAnswer()

And to get the variable using the dictionary do this:

value = getattr(self, self.slotDictionary[choice])

  • Related