-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatic_methods.py
More file actions
31 lines (23 loc) · 1.18 KB
/
static_methods.py
File metadata and controls
31 lines (23 loc) · 1.18 KB
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
# Static methods = methods that belong to the class rather than any object of the class
# Used for general utilitiy functions that don't require object-specific state or need access to any information
# Static methods are regular functions defined within the scope of a class.
# They are used for utility functions that are logically related to the class
# but do not require access to either instance-specific data or class-specific data. They operate purely on the arguments passed to them.
# Instance methods are best for operations on instances of the class
# Example
class Employee:
def __init__(self, name, position):
self.name = name
self.position = position
def get_information(self):
print(f"{self.name} is a {self.position}")
@staticmethod
def is_valid_position(position):
valid_positions = ["Cook", "Janitor", "Engineer", "Manager"]
return position in valid_positions
cook = Employee("Alex","Cook")
janitor = Employee("David","Janitor")
cook.get_information()
janitor.get_information()
print(Employee.is_valid_position("Engineer"))
print(cook.is_valid_position("Scientist")) # a static method can be called by an instance of the class