I am trying to understand how class attributes work in Python. I have confusion based on following example.
#!/usr/bin/python3
class Bag:
val = 100
items = []
def add(self, x):
self.items.append(x)
print(self.items)
b1 = Bag()
b1.add('book')
b1.val += 1
print(b1.val)
b1.add('pen')
b1.val += 1
print(b1.val)
b2 = Bag()
b2.add('sketches')
b2.val += 1
print(b2.val)
b2.add('text')
b2.val += 1
print(b2.val)
b2.add('canvas')
b2.val += 1
print(b2.val)
Output expected:
['book']
101
['book', 'pen']
102
['book', 'pen', 'sketches']
103
['book', 'pen', 'sketches', 'text']
104
['book', 'pen', 'sketches', 'text', 'canvas']
105
Output seen:
['book']
101
['book', 'pen']
102
['book', 'pen', 'sketches']
101
['book', 'pen', 'sketches', 'text']
102
['book', 'pen', 'sketches', 'text', 'canvas']
103
Why is there inconsistency between list being shared vs different copies of integers?
Here is another example that shows a different behavior for int
.
#!/usr/bin/python3
class Person:
cl_roll = 0
def __init__(self, name):
self.name = name
self.roll = self.next_roll()
print(self.roll, self.name)
@classmethod
def next_roll(cls):
cls.cl_roll += 1
return cls.cl_roll
p1 = Person('Eve')
p2 = Person('Abel')
p3 = Person('Eva')
Output expected based on previous output:
1 Eve
1 Abel
1 Eva
Actual output:
1 Eve
2 Abel
3 Eva
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…