I try to change the variable that will be changed by input. So if i call the function, i want to define the variable that will be changed by input. In one case variable "a" should be changed, in the other case i want to change variable "b". Is there an option to change "test.a" in the function def calc? To use check and change the variable by if request is not an option.
Thank you and best regards, Carl
class test:
a = 1
b = 2
def f(x):
return test.a*x test.b*x
def calc(x,change):
#change variable to be changed between "test.a" and "test.b" by input of "change"
test.a = 10
solution = test.f(x)
print(solution)
test.calc(1,"b")
CodePudding user response:
You can use setattr
function to accomplish this. After applying recommendations from my IDE, code looks like this:
class Test:
a = 1
b = 2
@staticmethod
def f(x):
return Test.a * x Test.b * x
@staticmethod
def calc(x, change):
# change variable to be changed between "test.a" and "test.b" by input of "change"
setattr(Test, change, x)
# check class variables after the change
print(Test.a)
print(Test.b)
solution = Test.f(x)
print(solution)
Test.calc(1, "b")