提示信息

Python __slots__

一分 已关注

The __slots__ attribute in Python is used to define the attributes of a class and restricts the creation of any additional attributes. It is a technique used to optimize memory usage and improve attribute access speed.

By using __slots__, we can define a fixed set of attributes for instances of a class. This is achieved by assigning a tuple of attribute names to the __slots__ attribute within the class definition. The attribute names listed in __slots__ will be the only attributes allowed for instances of the class, and any attempt to assign a value to an attribute that is not listed will raise an AttributeError.

Here is an example that demonstrates the use of __slots__:

  1. class Person:
  2. __slots__ = ('name', 'age')
  3. def __init__(self, name, age):
  4. self.name = name
  5. self.age = age
  6. person = Person('John', 25)
  7. person.name = 'Jane' # This is allowed since 'name' is defined in __slots__
  8. person.age = 30 # This is allowed since 'age' is defined in __slots__
  9. person.gender = 'Male' # This will raise an AttributeError since 'gender' is not defined in __slots__

In the above example, the Person class defines the name and age attributes in the __slots__ attribute. This means that instances of the Person class can only have these two attributes. Any attempt to assign or access attributes not listed in __slots__ will result in an AttributeError.

Using __slots__ can be beneficial in situations where we are working with a large number of instances of a class and want to reduce memory usage by not storing a __dict__ attribute for each instance. Additionally, attribute access can be faster when using __slots__ since the attribute lookup is simplified.

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
一分 关注 已关注

最近一次登录:2023-10-09 16:03:05   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图