Home >Backend Development >Python Tutorial >What\'s the Difference: Instance vs. Class Attributes in Python?
Impact of Variable Definition Within and Outside __init__() in Classes
In Python, class variables declared within the constructor function __init__() exhibit distinct behavior compared to those defined outside. Variables declared inside __init__() are instance attributes, while variables defined outside are class attributes.
Instance Attributes (Defined Inside __init__() with 'self')
Variables prepended with self within __init__() are associated with specific object instances. Each instance has its own copy of these variables. Therefore, changes made to these variables within one instance won't affect other instances.
Example:
<code class="python">class WithClass: def __init__(self): self.value = "Bob" def my_func(self): print(self.value)</code>
Here, value is an instance attribute. Each instance of WithClass will have its own value.
Class Attributes (Defined Outside __init__)
Variables defined outside __init__() are class attributes. These variables are shared among all instances of the class. Any changes made to them within one instance are reflected across all other instances.
Example:
<code class="python">class WithoutClass: value = "Bob" def my_func(self): print(self.value)</code>
In this case, value is a class attribute. All instances of WithoutClass will refer to the same value variable.
Consequences of Variable Definition
The choice between defining variables inside or outside __init__() depends on the desired functionality:
Improper use of these attributes can lead to unexpected behavior or errors. For instance, defining an attribute as an instance attribute when it should be a class attribute may inadvertently create multiple copies of the variable, leading to performance issues or data inconsistencies.
The above is the detailed content of What\'s the Difference: Instance vs. Class Attributes in Python?. For more information, please follow other related articles on the PHP Chinese website!