0

Within my class of categories, I have several functions that reference to a variable. For them to access the variable I had to make the variable global. It worked, it's fine, when there only is one object within the class. When it had two, the results blew. Other objects also had access to the global variable and changed its value. Is there a way I could set-up a global variable for the class methods but are unique to every class instances?

EDIT:

Thanks guys, I am now enlightened with using the __init__ method. There was no need to use global variables.

  • I don't understand: you want to make a global variable for each instance? – Dave Benson Jul 27 '20 at 08:48
  • Could you post some sample code? It sounds like you might be better off avoiding global variables, instead using the variable as an argument for the functions and returning the new result at the end. You may also want to look at having the variable as a property of the class (self.whatever) instead of being global - that will keep it unique to each class instance – LowIntHighCha Jul 27 '20 at 08:48
  • Does this answer your question? [Instance variables vs. class variables in Python](https://stackoverflow.com/questions/2714573/instance-variables-vs-class-variables-in-python) – Adam.Er8 Jul 27 '20 at 08:48
  • https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables – Adam.Er8 Jul 27 '20 at 08:49

2 Answers2

1

You can use method __init__ for difinition of variables for every instance of class. You can read more information here: https://www.tutorialspoint.com/What-is-difference-between-self-and-init-methods-in-python-Class

DD_N0p
  • 229
  • 1
  • 2
  • 6
0

If you have a class and you'd like variables to be shared in that class, you can do so in the __init__ function:

class Example:

    def __init__(self, a, b):
        self.a = a
        self.b = b

    def print_a(self):
        print(self.a)

example = Example(a = 5, b = 3)
example.print_a()
Nathan
  • 3,558
  • 1
  • 18
  • 38