Change class attributes from generic method

Asked

Viewed 163 times

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 name of the attribute 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 that the method is executed as follows:

instancia.altera_atributo('atr2', 10)

My difficulty is that python searches in the class, an attribute with the name "var_com_o_nome_do_attribute" and I don’t know 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 must be something simple, but I’m starting now and I’m not finding the solution.

  • 1

    So why make a class? Wouldn’t it be better to make a dictionary?

  • many of the "attributes" of the class are dictionaries... the method is precisely to facilitate access

  • 2

    I say use dictionary instead of class, if you want something dynamic access you don’t want a class. It is even possible to do what you want, but for what? Use the right tool for the task.

2 answers

0

Use the setattr. Your function altera_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)

0


Maniero’s comment helped me with the resolution. The class remains a class but similar attributes have been transformed into a single dictionary (as class attribute). I don’t know if it’s good practice but it’s solved.

  • Initially to use a dictionary as a class solved, but as it seemed a lot a POG, I went to study POO (in c# that I am more accustomed), it seemed to me a more elegant solution to use a subclass as attribute since only the values change, the indices are immutable and used in many places.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.