Home > OS >  Python, passing variable from function to class NameError: name 'var1' is not defined
Python, passing variable from function to class NameError: name 'var1' is not defined

Time:01-27

I try to pass a variable to class that was defined earlier. But it gives me an error, why? How can i fix it? I don't want to copy class inside every function that will use it.

class print_it():
    def __init__(self, *args):
        self.var1 = var1
        self.var2 = var2
        print(str(var1), str(var2))

def yolo():
    var1 = 1
    var2 = 2

    print_it(var1,var2)

yolo()

The only workable solution for me was putting class inside the function, defining variables globally doesn't work since it doesn't take new values. I've also tried this:

    pr = print_it()
    pr.var1(var1)
    pr.var2(var2)

CodePudding user response:

As @Tomerikoo already mentioned, just change the __init__ arguments. If you always only expect two variables like var1 and var2 then you can use this code:

class print_it:
    def __init__(self, var1, var2):
        self.var1 = var1
        self.var2 = var2
        print(str(var1), str(var2))

def yolo():
    var1 = 1
    var2 = 2

    print_it(var1,var2)

yolo()
  • Related