0

I want to create a class variable in python with arguments of the funtion

example :

class test:
    def __init__(self):
        self.name = "test"
        self.age = 20

    def get_variable (self, name, age):
        # this function should declare a variable which is name_age
        self.test_20 = 'some value'
        ##this self.test_20 will become my flag for the class 
        ## I want declare a variable which is test_20 from name and age argument of this function

t = test()
t.get_variable('test', 20)

#if I call t.test_20, it should return 'some value'


It seems easy but I am not able to get it done any help is appreciated

  • Not sure if this is the best practice, but you can just define the variable directly in the class (outside functions) class test: #Add variables here test_20 = 20 – AG-88301 Dec 25 '22 at 08:03
  • thanks for the response, but I need to set multiple flags like test_20 based on the arguments of the function get_variable that way I can avoid lots of if else statements – isapansoni Dec 25 '22 at 08:07
  • I think you are actually looking for [`setattr`](https://docs.python.org/3/library/functions.html#setattr) - see [thread](https://stackoverflow.com/questions/9561174/using-setattr-in-python) – metatoaster Dec 25 '22 at 08:19
  • yes setattr is solving my problem , didn't know about this – isapansoni Dec 27 '22 at 06:31

0 Answers0