Python OOP Tutorial 3: classmethods and staticmethods
Understanding Class Methods and Static Methods in Python
Introduction to Class and Static Methods
- The video introduces the topic of class methods and static methods, highlighting common confusion between the two.
- Regular methods take the instance as their first argument (commonly named
self). The discussion will focus on how to modify this behavior.
Creating a Class Method
- To convert a regular method into a class method, a decorator called
@classmethodis used. An example method namedset_raise_amountis created.
- This method takes the class (
cls) and an amount as arguments. It alters the functionality to receive the class instead of an instance.
Working with Class Variables
- In class methods, it’s conventional to use
clsas the variable name for the class. The keywordclasscannot be used due to its reserved status in Python.
- Inside
set_raise_amount, the class variableraise_amountis set usingcls.raise_amount = amount.
Demonstrating Class Method Functionality
- After creating instances of an employee, printing shows that all instances reflect changes made through the class variable.
- Changing
raise_amountfrom 4% to 5% demonstrates how callingemployee.set_raise_amount(5)updates all instances since they reference the same class variable.
Using Class Methods from Instances
- Although it's possible to call a class method from an instance, it’s not common practice. However, doing so still affects shared variables across instances.
Alternative Constructors with Class Methods
- Class methods can serve as alternative constructors by providing different ways to create objects based on specific input formats.
- An example scenario involves parsing employee information from strings separated by hyphens before creating new employee objects.
Practical Example: Parsing Strings for Employee Creation
- A demonstration shows splitting strings into first name, last name, and salary before passing them into an initializer for object creation.
Alternative Constructors in Python Classes
Creating an Alternative Constructor
- Introduces the concept of an alternative constructor for creating employee objects from a string input, typically prefixed with "from" as a naming convention.
- Defines a class method named
from_string, which accepts the class and an employee string to parse details like first name, last name, and pay.
- Explains how to split the provided employee string into components instead of using hardcoded values, enhancing flexibility.
- Demonstrates creating a new employee instance using the parsed variables and returning this object for further use.
- Concludes that users can now utilize the
from_stringmethod to create employee objects without manual parsing.
Real-world Example of Alternative Constructors
- Highlights that users no longer need to manually parse strings; they can simply call
from_stringwith their data.
- Discusses how this approach mirrors real-world examples found in modules like date/time, where similar constructors exist for creating date/time objects from various inputs.
Understanding Class Methods vs. Static Methods
Class Methods Explained
- Clarifies that class methods automatically receive the class as their first argument (referred to as CLS), differentiating them from regular instance methods.
Static Methods Overview
- Describes static methods as functions included within classes but do not receive any automatic arguments (neither instance nor class).
- Provides an example of a static method called
is_workday, which checks if a given date is a weekday without relying on any specific instance or class variable.
Implementing Static Method Logic
- Details how to implement logic within
is_workdayby utilizing Python's built-in weekday functionality to determine if a day falls on Saturday or Sunday.
Understanding Static Methods in Python
Exploring Method Types
- The speaker discusses the appropriateness of using static methods when the
selfvariable is not utilized, suggesting that developers should evaluate whether a static method would be more suitable than a class or instance method.
- An example is provided where the speaker imports the time module and creates a new date. They demonstrate how to use a static method to check if this date is a weekday by calling
employee.is_work_day(date).
Testing Static Method Functionality
- After running an initial test, an error occurs due to incorrect logic in checking weekdays. The speaker corrects it by ensuring that the condition checks for both Saturday (5) and Sunday (6).
- Upon correcting the input date, they confirm that their static method correctly identifies Monday as a workday, returning true. This illustrates practical application and testing of static methods.
Summary of Key Concepts
- The video concludes with a summary of different types of methods: instance methods, class methods (which can serve as alternative constructors), and static methods (which do not operate on instances or classes).