1
class Person(object):
kind = 'human'
def __init__(self, name):
self.name = name
def who_are_you(self):
print(self.name, self.kind)
p1 = Person('A')
p2 = Person('B')
p1.who_are_you()
p2.who_are_you()
Execution result of 1
A human
B human
The class variable (kind in this case) is It is shared by all the created objects.
2
class T(object):
words = []
def add_word(self, word):
self.words.append(word)
c = T()
c.add_word('apple')
c.add_word('banana')
print(c.words)
d = T()
d.add_word('orange')
d.add_word('cake')
print(d.words)
Execution result of 2
['apple', 'banana']
['apple', 'banana', 'orange', 'cake']
I created two objects, an object called c and an object called d, Because words is a class variable It has been shared by c and d.
This can lead to bugs.
To prevent this
Initialize (assign to an instance variable) with __init__
each time.
3
class T(object):
def __init__(self):
self.words = []
def add_word(self, word):
self.words.append(word)
c = T()
c.add_word('apple')
c.add_word('banana')
print(c.words)
d = T()
d.add_word('orange')
d.add_word('cake')
print(d.words)
Execution result of 3
['apple', 'banana']
['orange', 'cake']
Recommended Posts