1

Ok, this is probably really simple but I'm struggling. So, let's say I have a simple class "Simple" that has some attributes a and b. And I have a method, "trim" that can be used on one attribute at a time:

class Simple():

    def __init__(self, a=None, b=None):

        self.a = a
        self.b = b

    def trim(self.[???]):
        ...do some stuff...
        return self

Now, I want the user to be able to apply the method to any of the attributes (i.e., a and b) with something like:

simple_with_a_trimmed = simple.trim('a')

or

simple_with_b_trimmed = simple.trim('b')

How can I set up the method so that I can pass it the appropriate attribute? Thanks in advance for any thoughts!

1 Answer 1

1

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"`
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.