Skip to content

Commit 9bd19ef

Browse files
committed
Static methods
1 parent b52b8f8 commit 9bd19ef

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Diff for: static_methods.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# When we want to access a method without an object, you can use the @staticmethod
2+
# @staticmethod makes the method immediately below it a static method.
3+
# A static method does not belong to the object and hence does not have the `self` attribute.
4+
# In other words the first parameter is NOT considered as an implicit reference to the object
5+
# and hence it cannot access the self attributes of an object of its class.
6+
7+
class Employee:
8+
__no_of_employees = 0
9+
def __init__(self, emp_name, emp_age):
10+
self.name = emp_name
11+
self.age = emp_age
12+
def employee_login(self):
13+
Employee.__no_of_employees += 1
14+
@staticmethod
15+
def get_total_employees():
16+
return Employee.__no_of_employees
17+
# We can pass parameters to the constructor and set the instance variables values.
18+
raj=Employee("Raj", 28)
19+
raj.employee_login()
20+
pradeep=Employee("Pradeep", 27)
21+
pradeep.employee_login()
22+
kumar=Employee("Kumar", 27)
23+
kumar.employee_login()
24+
print("Total employees logged in via classname : ", Employee.get_total_employees())
25+
# Static methods can be accessed/invoked using object reference
26+
# But its a good practice to invoke a static method using class name.
27+
print("Total employees logged in reference variable : ", kumar.get_total_employees())

0 commit comments

Comments
 (0)