python class member vs instance member

python class member vs instance member

Guide

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import time

class Info(object):
rects = [] # by ref (object): all instances has only 1 same copy.
counter = 0 # by value: all instances has 1 different copy
def __init__(self):
self.new_rects = []
self.new_counter = 0

def func():
it = Info()
return it

def test1():
info = func()

info.rects.extend([1,2,3,4,5])
info.counter += 1
info.new_rects.extend([1,2,3,4,5])
info.new_counter += 1

print("rect size", len(info.rects),len(info.new_rects))
print("counter", info.counter,info.new_counter)
print("--------------------------")

info2 = func()
info2.rects.extend([1,2,3,4,5])
info2.counter += 1
info2.new_rects.extend([1,2,3,4,5])
info2.new_counter += 1

print("rect size", len(info2.rects),len(info2.new_rects))
print("counter", info2.counter,info2.new_counter)
print("--------------------------")



if __name__ == "__main__":
test1()

"""
rect size 5 5
counter 1 1
--------------------------
rect size 10 5
counter 1 1
--------------------------
"""

Reference

History

  • 20190927: created.
赞赏