You can use the get getattr and setattr methods. These allow you to refer to a class attribute by a string.
You can pass the desired attribute to the trim method. You can then retrieve the value of the specified attribute using getattr. Then, you can either transform it, and return it, or perhaps modify it using setattr -- to update the object.
Below is a simple example of this in action. The trim1 method merely returns the value of the (transformed) attribute but does not update the object. The trim2 method changes the object itself -- it updates the value of the specified attribute.
I've also added a __str__ method to show how the object changes after each call.
class Simple:
def __init__(self, a=None, b=None):
self.a = a
self.b = b
def trim1(self, attr):
# Get value of the attribute
current_value = getattr(self, attr)
# Transform and return the value of the attribute
# Removing whitespace as an example
return current_value.strip()
def trim2(self, attr):
# Get value of the attribute
current_value = getattr(self, attr)
# Transform the value of the attribute
# Removing whitespace as an example
current_value = current_value.strip()
# Update the value of the attribute
setattr(self, attr, current_value)
def __str__(self):
return f'a: "{self.a}", b: "{self.b}"'
# Create an object of type Simple
simple = Simple(' data1', 'data2 ')
# These methods do not change the object, but return the transformed value
a = simple.trim1('a')
b = simple.trim1('b')
print(f'Returned value of a: "{a}"')
print(f'Returned value of b: "{b}"')
print(simple) # Prints `a: " data1", b: "data2 "`
# Apply the transformation to attribute `a`
simple.trim2('a')
print(simple) # Prints `a: "data1", b: "data2 "`
# Apply the transformation to attribute `b`
simple.trim2('b')
print(simple) # Prints `a: "data1", b: "data2"`