Home > Article > Backend Development > How Do Variable Scopes Work in Python Classes?
Understanding Variable Scopes in Python Classes
Declaring variables in Python classes can be confusing at first. This article aims to clarify the different scopes and nuances associated with variable declaration in class contexts.
General Scope Rules:
Instance Variables vs. Global Variables:
Instance variables (declared using self.(variable name)) behave differently from global variables (declared outside any function or class). While everything declared within a class is technically public, instance variables are bound to the individual object instance.
Example:
class Test: a = None # Class variable b = None # Class variable def __init__(self, a): self.a = a # Instance variable
In this example, the class variables a and b are accessible to all class functions. However, the instance variable self.a is specific to each object instance. Setting self.a in __init__ does not affect the class variable a.
Protected Variables:
Although Python does not explicitly define private or protected variables, variables prefixed with an underscore (_) are considered protected. Technically, they are still accessible outside the class, but mangling their names discourages access.
Private Variables:
Variables prefixed with double underscores (__) are considered private. Their names are mangled to make it difficult to access them directly outside the class.
Additional Nuances:
The above is the detailed content of How Do Variable Scopes Work in Python Classes?. For more information, please follow other related articles on the PHP Chinese website!