Python Trick: The Magic of __slots__

王林
Release: 2024-08-28 18:32:33
Original
701 people have browsed it

Python Trick: The Magic of __slots__

Python’s flexibility with dynamic attributes is one of its strengths, but sometimes you want to optimize memory usage and performance.

Enter slots, a feature that allows you to define a fixed set of attributes for your class, reducing memory overhead and potentially speeding up attribute access.


How It Works

Normally, Python objects are implemented as dictionaries for storing attributes, which can lead to higher memory consumption.

By defining slots in your class, you instruct Python to use a more memory-efficient internal structure.

This is especially useful when you know the attributes a class will have ahead of time and want to avoid the overhead of a full dictionary.

Here’s a demonstration of how to use slots:

class Point:
    __slots__ = ['x', 'y']  # Define the allowed attributes

    def __init__(self, x, y):
        self.x = x
        self.y = y


# Create a Point instance
p = Point(10, 20)

print(p.x)  # Output: 10
print(p.y)  # Output: 20

# Attempting to add a new attribute will raise an AttributeError
try:
    p.z = 30
except AttributeError as e:
    print(e)  # Output: 'Point' object has no attribute 'z'

# Output:
# 10
# 20
# 'Point' object has no attribute 'z'
Copy after login

In this example, slots restricts the Point class to only the x and y attributes.

Attempting to set any attribute not listed in slots results in an AttributeError.


Why It’s Cool

Using slots can lead to significant memory savings, especially when creating large numbers of instances, by eliminating the overhead of the attribute dictionary.

It can also improve attribute access speed.

However, be cautious: slots can limit some dynamic capabilities of Python objects and may not be suitable for all use cases.

The above is the detailed content of Python Trick: The Magic of __slots__. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!