Imagine a code like this:
sample.py
class Sample:
sample_list = []
def __init__(self, args1):
self.name = args1
def add_args(self, args2):
self.sample_list.append(args2)
When I run this code, the sample_list is shared between a and b as shown below.
>>> a = Sample('a')
>>> b = Sample('b')
>>> a.add_args('hoge')
>>> b.add_args('huga')
>>> a.sample_list
['hoge', 'huga']
You can prevent this problem by designing the class with instance variables as follows.
sample.py
class Sample:
def __init__(self, args1):
self.name = args1
self.sample_list = []
def add_args(self, args2):
self.sample_list.append(args2)
Execution result
>>> a = Sample('a')
>>> b = Sample('b')
>>> a.add_args('hoge')
>>> b.add_args('huga')
>>> a.sample_list
['hoge']
>>> b.sample_list
['huga']
Classes-Python 3.8.5 documentation
Recommended Posts