File tree 1 file changed +33
-3
lines changed 1 file changed +33
-3
lines changed Original file line number Diff line number Diff line change 1
1
#!/usr/bin/env python
2
2
3
- # 27 -classmethod-1 .py
3
+ # 28 -classmethod-2 .py
4
4
5
5
# Classmethods are decorators which are inbuilt in Python.
6
6
# We decorate a function as a classemethod using the decorator
7
7
# @classmethod.
8
8
9
- # Class methods are used for functions which need not be
9
+ # Class methods are used for functions which need not be
10
10
# called via an instance. Certain use cases may be:
11
11
12
12
# a) Creating instances take resources, hence the methods/functions
13
- # which need necessarily
13
+ # which need necessarily
14
+
15
+
16
+ class InstanceCounter (object ):
17
+ count = 0
18
+
19
+ def __init__ (self , val ):
20
+ self .val = val
21
+ InstanceCounter .count += 1
22
+
23
+ def set_val (self , newval ):
24
+ self .val = newval
25
+
26
+ def get_val (self ):
27
+ return self .val
28
+
29
+ @classmethod
30
+ def get_count (cls ):
31
+ return cls .count
32
+
33
+ a = InstanceCounter (10 )
34
+ print ("\n Value of object : %s" % a .get_val ())
35
+ print (InstanceCounter .get_count ())
36
+
37
+ b = InstanceCounter (20 )
38
+ print ("\n Value of object : %s" % b .get_val ())
39
+ print (InstanceCounter .get_count ())
40
+
41
+ c = InstanceCounter (40 )
42
+ print ("\n Value of object : %s" % c .get_val ())
43
+ print (InstanceCounter .get_count ())
You can’t perform that action at this time.
0 commit comments