Python OOP Tutorial 3: classmethods and staticmethods

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 @classmethod is used. An example method named set_raise_amount is 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 cls as the variable name for the class. The keyword class cannot be used due to its reserved status in Python.
  • Inside set_raise_amount, the class variable raise_amount is set using cls.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_amount from 4% to 5% demonstrates how calling employee.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_string method 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_string with 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_workday by 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 self variable 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).
Video description

In this Python Object-Oriented Tutorial, we will be learning about classmethods and staticmethods. Class methods are methods that automatically take the class as the first argument. Class methods can also be used as alternative constructors. Static methods do not take the instance or the class as the first argument. They behave just like normal functions, yet they should have some logical connection to our class. We will look at some examples of both of these in order to understand both in depth. Let's get started. Python OOP 1 - Classes and Instances - https://youtu.be/ZDa-Z5JzLYM Python OOP 2 - Class Variables - https://youtu.be/BJ-VvGyQxho Python OOP 3 - Classmethods and Staticmethods - https://youtu.be/rq8cL2XMM5M Python OOP 4 - Inheritance - https://youtu.be/RSl87lqOXDE Python OOP 5 - Special (Magic/Dunder) Methods - https://youtu.be/3ohzBxoFHAY Python OOP 6 - Property Decorators - https://youtu.be/jCzT9XFZ5bw The code from this video can be found at: https://github.com/CoreyMSchafer/code_snippets/tree/master/Object-Oriented ✅ Support My Channel Through Patreon: https://www.patreon.com/coreyms ✅ Become a Channel Member: https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join ✅ One-Time Contribution Through PayPal: https://goo.gl/649HFY ✅ Cryptocurrency Donations: Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3 Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33 Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot ✅ Corey's Public Amazon Wishlist http://a.co/inIyro1 ✅ Equipment I Use and Books I Recommend: https://www.amazon.com/shop/coreyschafer ▶️ You Can Find Me On: My Website - http://coreyms.com/ My Second Channel - https://www.youtube.com/c/coreymschafer Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Instagram - https://www.instagram.com/coreymschafer/ #Python