Source: Andrew George on Unsplash
Regular methods automatically pass the instance of the class as the first argument, conventionally named self
.
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = f'{first}.{last}@company.com'
def fullname(self):
return f'{self.first} {self.last}'
In the fullname
method, self
refers to the instance of the Employee
class.
Class methods, on the other hand, receive the class itself as the first argument, conventionally named cls
. To define a class method, we use the @classmethod
decorator.
class Employee:
raise_amount = 1.04
def __init__(self, first, last, pay):
self.first = first
# ...
@classmethod
def set_raise_amount(cls, amount):
cls.raise_amount = amount
Here, set_raise_amount
is a class method that modifies the class variable raise_amount
You can call class methods using the class name:
Employee.set_raise_amount(1.05)
print(Employee.raise_amount) # Output: 1.05
Class methods are also used as alternative constructors, allowing for different ways to create objects
class Employee:
# ...
@classmethod
def from_string(cls, emp_str):
first, last, pay = emp_str.split('-')
return cls(first, last, pay)
emp_str_1 = 'John-Doe-50000'
emp_1 = Employee.from_string(emp_str_1)
print(emp_1.email) # Output: John.Doe@company.com
The from_string
method parses a string and creates an Employee
object.
Static methods do not automatically pass either the instance or the class as the first argument. They are similar to regular functions but are included within a class because they have some logical connection to the class. We use the @staticmethod
decorator to define them.
import datetime
class Employee:
# ...
@staticmethod
def is_workday(day):
# Monday: 0, Sunday: 6
if day.weekday() == 5 or day.weekday() == 6:
return False
return True
my_date = datetime.date(2023, 11, 13) # Monday
print(Employee.is_workday(my_date)) # Output: True
The is_workday
method checks if a given date is a workday.
self
) as the first argument.cls
) as the first argument, often used for alternative constructors.Understanding when to use regular, class, and static methods is essential for writing clean and efficient Python code. Class methods provide flexibility in object creation, while static methods offer a way to include utility functions within a class context.