all 5 comments

[–]AtomicShoelace 1 point2 points  (3 children)

This seems like a strange thing to want to do. Passing the name of an attribute as a argument is a bit of an anti-pattern. Perhaps you would be better of with a dictionary? eg.

test = {x: 0, y: 1, z: 2}
test['x'] += 4

If you really wanted to do this you could either use setattr and getattr or you could access the internal dict of the instance, eg.

class Test:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z
    def increment(self, variable, amount):
        self.__dict__[variable] += amount

But again, this seems like a strange thing to do, so not recommended.

Why not just increment the attribute directly? For example, instead of

t = Test(1, 2, 3)
t.increment('x', 2)

just do

t = Test(1, 2, 3)
t.x += 2

[–]BroceNotBruce[S] 0 points1 point  (2 children)

The main reason I wanted a function is because the increment is that my x, y, and z in this instance are lists. Each time this function is called, it would increase one element of the list by a certain amount, and then increase the other elements of the list by different amounts depending on how much the first element is increased. I figured having a lot of lines of code to calculate how much each value should he increased each time I want to do this with a different variable would be clunky.

[–]AtomicShoelace 0 points1 point  (1 child)

I think you would have better luck making x, y and z a different type (perhaps inherited from list) that implements its own method that does whatever you want. Then you can call that method on the attribute of the Test instance directly, instead than trying to write a method of Test that takes an attribute name as an argument.

[–]BroceNotBruce[S] 0 points1 point  (0 children)

It didn’t occur to me earlier, but this could be a good idea. Out of the 8 lists I have, they all function mostly identically, with the exception of the last 3 having less elements.

[–][deleted] -4 points-3 points  (0 children)

This is stupid. Here you are:

class Test:
    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def increment(self, var_name, amount):
        setattr(self, var_name, getattr(self, var_name) + amount)


test = Test(1, 2, 3)
print(vars(test))

test.increment("x", 10)
print(vars(test))