in class instance method write object propery names in list namned 'names'. loop through list and increment property value by one with self.names[i] += 1 in python

You can define an instance method in a class and create a list of property names called names inside that method. Then, you can loop through the list using a for loop and increment each property by one using self.

Here's an example implementation:

main.py
class MyClass:
    def __init__(self, name1, name2, name3):
        self.property1 = 0
        self.property2 = 0
        self.property3 = 0
        self.names = [name1, name2, name3]

    def increment_properties(self):
        for i in range(len(self.names)):
            setattr(self, self.names[i], getattr(self, self.names[i]) + 1)
337 chars
11 lines

In this code, we defined a class called MyClass with three properties named property1, property2, and property3. We also defined a list called names with the names of these three properties.

Inside the increment_properties method, we loop through the names list using a for loop and increment each property by one using setattr and getattr functions. These functions allow us to set and get attribute values by name.

You can now create an instance of this class and call the increment_properties method to increment the properties:

main.py
my_object = MyClass("property1", "property2", "property3")
print(my_object.property1, my_object.property2, my_object.property3)  # Output: 0 0 0

my_object.increment_properties()
print(my_object.property1, my_object.property2, my_object.property3)  # Output: 1 1 1
265 chars
6 lines

gistlibby LogSnag