Properties, descriptors, and slots

Properties, descriptors, and slots

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:36

Nortren·

What is a property in Python?

0:16
A property is a way to expose attribute-like access while running custom code on get, set, or delete. It is defined using the property decorator on a getter method, with optional setter and deleter. Properties allow you to add validation or computation while preserving a clean attribute interface.

When should you use a property versus a regular attribute?

0:15
Use a regular attribute when there is no need for computation, validation, or side effects. Use a property when access requires logic, when you want to compute the value on demand, when you need to maintain backward compatibility while adding behavior, or when an attribute should be read-only.

What is a descriptor?

0:16
A descriptor is an object that defines dunder get, dunder set, or dunder delete and is stored as a class attribute. When accessed through an instance, Python calls the descriptor's methods instead of returning the attribute directly. Properties, methods, and class methods are all implemented using descriptors.

What is the difference between a data descriptor and a non-data descriptor?

0:17
A data descriptor defines both dunder get and dunder set, possibly also dunder delete. A non-data descriptor defines only dunder get. Data descriptors take precedence over instance attributes during lookup, while instance attributes take precedence over non-data descriptors. Properties are data descriptors.

What are slots?

0:16
Slots is a class attribute that restricts the attributes an instance can have. Defining slots replaces the default per-instance dict with a fixed-size structure, reducing memory usage and slightly speeding up attribute access. It is useful for classes with many instances, but it disables dynamic attribute addition.

What are the trade-offs of using slots?

0:16
Slots reduce memory overhead and speed up attribute access. The downsides are that you cannot add new attributes at runtime, weak references require explicit declaration, multiple inheritance with slots is restricted, and pickling can be more complex. Use slots when memory matters and dynamic attributes are not needed. ---