Skip to content

Commit 7e881dd

Browse files
author
Vimal
committed
* Updated 28-classmethod-2.py
1 parent dd9c5b3 commit 7e881dd

File tree

1 file changed

+33
-3
lines changed

1 file changed

+33
-3
lines changed

28-classmethod-2.py

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,43 @@
11
#!/usr/bin/env python
22

3-
# 27-classmethod-1.py
3+
# 28-classmethod-2.py
44

55
# Classmethods are decorators which are inbuilt in Python.
66
# We decorate a function as a classemethod using the decorator
77
# @classmethod.
88

9-
# Class methods are used for functions which need not be
9+
# Class methods are used for functions which need not be
1010
# called via an instance. Certain use cases may be:
1111

1212
# 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("\nValue of object : %s" % a.get_val())
35+
print(InstanceCounter.get_count())
36+
37+
b = InstanceCounter(20)
38+
print("\nValue of object : %s" % b.get_val())
39+
print(InstanceCounter.get_count())
40+
41+
c = InstanceCounter(40)
42+
print("\nValue of object : %s" % c.get_val())
43+
print(InstanceCounter.get_count())

0 commit comments

Comments
 (0)