dyingplanet
dyingplanet

Reputation: 1

Is there a way to use an input to select a class member variable?

I'm trying to do the following where I use an input variable number to select an object in a class. Is there a way to do this in Python? I'm thinking of how you can do something similar with strings in python. with print(f"Hello World {some_variable}")

class thing():
  obj1 = 1
  obj2 = 2
  obj3 = 3


def(thing_class, number):
  thing_class.obj{number} = 10

Upvotes: 0

Views: 33

Answers (1)

fsimonjetz
fsimonjetz

Reputation: 5802

IIUC, you can use setattr, something like:

class Thing:
    obj1 = 1
    obj2 = 2
    obj3 = 3

def thing_setter(thing_class, number, value):
    # sets the attribute selected by the string to value
    setattr(thing_class, f"obj{number}", value)

Test:

>>> my_thing = Thing()
>>> my_thing.obj1
1
>>> thing_setter(my_thing, 1, 10)
>>> my_thing.obj1
10

Upvotes: 1

Related Questions