Instance-Specific Data in Classes
In object-oriented programming, it's possible for instances of a class to share data. This can be undesirable when you want each instance to maintain its own distinct data.
Suppose we have the following class:
class A: list = []
When we create instances of this class, all of them share the same list attribute:
>>> x = A() >>> y = A() >>> x.list.append(1) >>> y.list.append(2) >>> print(x.list) [1, 2] >>> print(y.list) [1, 2]
To avoid this behavior and provide separate instances for each object, we can modify the class declaration:
class A: def __init__(self): self.list = []
By declaring list within the __init__ method, we create a new instance of list for each new instance of A. This ensures that each instance of A has its own independent list attribute:
>>> x = A() >>> y = A() >>> x.list.append(1) >>> y.list.append(2) >>> print(x.list) [1] >>> print(y.list) [2]
The above is the detailed content of How Can I Ensure Instance-Specific Data in Python Classes?. For more information, please follow other related articles on the PHP Chinese website!