Variables Within and Outside init
The location where you declare a variable within a Python class can significantly impact its behavior. Consider the following two classes:
<code class="python">class WithClass(): def __init__(self): self.value = "Bob" def my_func(self): print(self.value) class WithoutClass(): value = "Bob" def my_func(self): print(self.value)</code>
Class Variables vs. Instance Variables
The main difference between these two classes lies in where the variable value is declared. In WithClass, it is declared within the __init__ method, making it an instance variable. This means that each instance of WithClass will have its own independent copy of the value attribute.
On the other hand, in WithoutClass, the value attribute is declared outside of the __init__ method, making it a class variable. As a result, all instances of WithoutClass will share the same single instance of the value attribute.
Initializer Methods
The __init__ method in WithClass serves as the initializer for each object instance. When an instance is created, the __init__ method is called and the self.value attribute is assigned the value "Bob." This value is then stored in the instance and is available to other methods within the object.
Consequences
The decision of where to declare a variable can have implications for your program's behavior. If you need each instance of a class to have its own unique value for a particular attribute, it should be declared within the __init__ method as an instance variable. Alternatively, if all instances of a class should share the same value for an attribute, it can be declared outside of the __init__ method as a class variable.
Therefore, the critical distinction is whether you want the variable to be shared among all instances of the class (class variable) or to be unique to each individual instance (instance variable).
The above is the detailed content of Instance vs. Class Variables: Where Should You Declare Variables in Python?. For more information, please follow other related articles on the PHP Chinese website!