Search code examples
pythonmemberselfiterablemutable

looping through member variables and changing their type (in Python)?


Is it possible to iterate theough some member variables of a defined class, and then change the member variable type?

For instance something like the below:

def __init__(self, a, b, c):
    self.A = a
    self.B = b
    self.C = c
    self.memberVarsToChange = {self.A: float, self.B: float}

def convertTypes(self):
    for item, t in self.memberVarsToChange.items():
        item = t(item)

The item obviously doesn't refer to the member variable, it's local to the loop. Is there a way to refer to the actual member variable?

Many thanks.


Solution

  • FYI, in Python member variables are called attributes.

    You need to store the attribute names in self.memberVarsToChange, not the attribute values. Then you can use getattr() and setattr() to update the attributes dynamically.

    def __init__(self, a, b, c):
        self.A = a
        self.B = b
        self.C = c
        self.memberVarsToChange = {"A": float, "B": float}
    
    def convertTypes(self):
        for attr, t in self.memberVarsToChange.items():
            setattr(self, attr, t(getattr(self, attr)))