File tree Expand file tree Collapse file tree 1 file changed +25
-3
lines changed Expand file tree Collapse file tree 1 file changed +25
-3
lines changed Original file line number Diff line number Diff line change @@ -15,10 +15,32 @@ def show_num_of_chairs(self):
15
15
print (Car .num_of_chairs ) # Access class variable
16
16
17
17
18
- car = Car ('blue' , 'OP90' , '190mph' )
18
+ car_1 = Car ('blue' , 'OP90' , '190mph' )
19
+ car_2 = Car ('brown' , 'I8' , '100mph' )
19
20
# Let us see the instance variable of this object:
20
- print (car .__dict__ )
21
+ print (car_1 .__dict__ )
21
22
22
23
print (Car .num_of_chairs )
23
24
# The instance will first check whether it has the 'num_of_chairs; instance variable, then it checks whether it is a class variable
24
- print (car .num_of_chairs )
25
+ print (car_1 .num_of_chairs )
26
+ print ()
27
+
28
+ # Following is interesting:
29
+
30
+ # If we change num_of_chairs using the class:
31
+ Car .num_of_chairs = 5
32
+
33
+ print (Car .num_of_chairs )
34
+ print (car_1 .num_of_chairs )
35
+ print (car_2 .num_of_chairs )
36
+ print ()
37
+
38
+ # But if I change using one of the instances:
39
+ car_1 .num_of_chairs = 4
40
+
41
+ print (Car .num_of_chairs )
42
+ print (car_1 .num_of_chairs )
43
+ print (car_2 .num_of_chairs )
44
+
45
+ # This is because the line 'car_1.num_of_chairs = 4' creates a new instance variable for the object car_1
46
+ print (car_1 .__dict__ )
You can’t perform that action at this time.
0 commit comments