Change class attributes from generic method

0

I have a class with many attributes and would like to be able to change these attributes from a generic method where you must pass the attribute name to be changed and the new value.

class Classe_com_muitos_atributos:
   def __init__(self, atr1, atr2, atr4 ...):
      self.atr1 = 5
      self.atr2 = 5
      self.atr3 = 5
      self.atr4 = 5
      #muitos atributos...

   def altera_atributo(self, var_com_o_nome_do_atributo, valor):
      self.var_com_nome_do_atributo = valor

The idea is for the method to run as follows:

instancia.altera_atributo('atr2', 10)

My problem is that python looks in the class for an attribute named "var_with_at_attack_name" and I'm not sure how to do it so that instead it looks in the class for the attribute that is contained in the variable, in this example, atr2.

I imagine it should be something simple, but I'm starting now and I'm not finding the solution.

    
asked by anonymous 23.10.2018 / 00:00

1 answer

0

Use the setattr . Your function changes attribute will look like this:

def altera_atributo(self, var_com_o_nome_do_atributo, valor):
  setattr(self, var_com_o_nome_do_atributo, valor)
    
23.10.2018 / 02:41