In Python, we can define the variable outside the class, inside the class and even inside the methods. Let’s see, how to use and access these variables throughout the program.
Variable defined outside the class:
The variables that are defined outside the class can be accessed by any class or any methods in the class by just writing the variable name.
Outside_class1 outside_class Outside_class2 outside_class Outside_class3 outside_class Outside_class4 outside_class Outside_class5 outside_class
Variable defined inside the class:
The variables that are defined inside the class but outside the method can be accessed within the class(all methods included) using the instance of a class. For Example – self.var_name.
If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class.
Inside_class2 inside_class Inside_class3 inside_class
The statements which are marked as error will produce an error upon execution as the variable is not accessible there.
Variable defined inside the method:
The variables that are defined inside the methods can be accessed within that method only by simply using the variable name. Example – var_name.
If you want to use that variable outside the method or class, you have to declared that variable as a global.
The statements which are marked as error will produce error upon execution as the variable is not accessible there.
- class method vs static method in Python
- Python: Call Parent class method
- Protected variable in Python
- __name__ (A Special variable) in Python
- Python | Variable list slicing
- Python | Check if variable is tuple
- Python | Check if a variable is string
- Python | Accessing variable value from code scope
- Print Single and Multiple variable in Python
- Python | Set 6 (Command Line and Variable Arguments)
- Python Program to swap two numbers without using third variable
- Python | setting and retrieving values of Tkinter variable
- Python | Convert 1D list to 2D list of variable length
- self in Python class
- Class as decorator in python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.