Class methods, static methods, and metaclasses

Class methods, static methods, and metaclasses

Explore the power of functions and object-oriented programming in Python. This section delves into function definitions, class structures, and advanced topics such as properties and descriptors, ensuring you understand how to create robust and reusable code.

6 audio · 1:29

Nortren·

What is a class method?

0:13
A class method is a method that receives the class as its first argument instead of an instance. It is declared with the classmethod decorator. Class methods are commonly used as alternative constructors and for operations that act on the class itself rather than an instance.

What is a static method?

0:14
A static method is a method that receives neither the instance nor the class as an implicit first argument. It is declared with the staticmethod decorator. It behaves like a regular function but is namespaced inside the class. Use it for utility functions logically related to the class.

When would you use a class method as an alternative constructor?

0:14
Class methods are ideal for alternative constructors that build instances from different inputs. For example, a Date class might have from_string and from_timestamp class methods that parse their arguments and call the regular init. This pattern is common in the standard library, including in datetime.

What is a metaclass?

0:17
A metaclass is the class of a class. Just as a class defines how instances behave, a metaclass defines how classes behave. The default metaclass is type. You can create custom metaclasses by subclassing type and overriding methods like dunder new and dunder init to customize class creation.

When should you use a metaclass?

0:15
Metaclasses are powerful but rarely needed. They are appropriate for frameworks that need to register subclasses, enforce constraints across a class hierarchy, or generate code at class creation time. For most cases, class decorators or dunder init subclass are simpler alternatives.

What is dunder init subclass?

0:16
Dunder init subclass is a method called whenever a class is subclassed. It is a simpler alternative to metaclasses for many use cases. The base class can use it to register subclasses, validate them, or add features. It was introduced in Python 3.6 to reduce the need for full metaclasses. ---