-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass-instance-attributes-1.py
50 lines (38 loc) · 916 Bytes
/
class-instance-attributes-1.py
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
# class-instance-attributes-1.py
# This code shows that an Instance can access it's own
# attributes as well as Class attributes.
# We have a class attribute named 'count', and we add 1 to
# it each time we create an instance. This can help count the
# number of instances at the time of instantiation.
class InstanceCounter(object):
count = 0
def __init__(self, val):
self.val = val
InstanceCounter.count += 1
def set_val(self, newval):
self.val = newval
def get_val(self):
print(self.val)
def get_count(self):
print(InstanceCounter.count)
a = InstanceCounter(5)
b = InstanceCounter(10)
c = InstanceCounter(15)
for obj in (a, b, c):
print("value of obj: %s" % obj.get_val())
print("Count : %s" % obj.get_count())
'''
O/P-
5
value of obj: None
3
Count : None
10
value of obj: None
3
Count : None
15
value of obj: None
3
Count : None
'''