python的__slots__使用

使用__slots__
使用原因
python是动态语言,可以动态的对已经定义好的对象进行增加,修改属性操作
作用
在类中定义,采用tuple限制了该类的动态属性定义
实例
#限制Student类只可以增加name,age属性
class Student(object):
    __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
因为score没有在__slots__中定义,所以实例化Student,动态添加score时出现“AttributeError”错误
>>> s = Student() # 创建新的实例
>>> s.name = 'syy' # 绑定属性'name'
>>> s.age = 30 # 绑定属性'age'
>>> s.score = 99 # 绑定属性'score'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'
==注意:==如子类继承了有__slots__定义的父类,且没有在子类中实现__slots__,那么父类定义的__slots__不会影响子类;如果子类实现了__slots__那么子类实例化后,添加属性的限制范围为,父类和子类__slots__定义的集合
#子类没有实现__slots__
>>> class A(Student):
...     pass
...
>>> g = A()
>>> g.name = 'fff'
>>> g.name
'fff'
>>> g.score = 98
>>> g.score
98
#子类实现__slots__,且不新增
>>> class C(Student):
...     __slots__ = ()
...
>>> s = C()
>>> s.name = 'sss'
>>> s.name
'sss'
>>> s.score = 89
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'score'

#子类实现__slots__,且新增
>>> class D(Student):
...     __slots__ = ('score')
...
>>> d = D()
>>> d.score = 32
>>> d.score
32
>>> d.sxe
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'D' object has no attribute 'sxe'
>>> d.sxe = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'D' object has no attribute 'sxe'
### Python `__slots__` 的用法和作用 #### 定义与基本概念 在Python类定义中,可以通过设置特殊属性`__slots__`来限定实例可以拥有的属性名称列表。这不仅有助于减少内存占用,还能提高属性访问速度。 当声明了一个包含`__slots__`变量的类之后,该类创建的对象将无法动态添加新的成员变量[^1]。 ```python class MyClassWithSlots: __slots__ = ['name', 'identifier'] def __init__(self, name, identifier): self.name = name self.identifier = identifier ``` 上述代码展示了如何通过指定`__slots__`仅允许对象拥有特定的名字(name)和标识符(identifier),任何尝试给此类实例增加其他未列于`__slots__`中的属性都会引发异常。 对于不使用`__slots__`的情况: ```python class RegularClassWithoutSlots: def __init__(self, value): self.value = value instance_without_slots = RegularClassWithoutSlots(42) instance_without_slots.new_attribute = "This works fine" print(instance_without_slots.new_attribute) # 输出: This works fine ``` 而如果试图向具有`__slots__`约束的类实例分配额外属性,则会抛出错误: ```python my_instance_with_slots = MyClassWithSlots('example_name', 123456) try: my_instance_with_slots.unexpected_attr = True except AttributeError as e: print(e) # 输出类似于:'MyClassWithSlots' object has no attribute 'unexpected_attr' ``` #### 使用场景及其优势 - **节省空间**: 对于大量小型类实例的应用程序来说非常重要;因为每个实例不再需要字典(dict)存储其状态,而是直接利用固定大小的数据结构。 - **性能提升**: 访问受控字段的速度更快,由于这些字段的位置是预先确定好的,在某些情况下能带来显著效率增益。 - **防止误操作**: 可以有效阻止开发者无意间修改不该被改变的状态信息,增强了代码的安全性和可维护性。 需要注意的是,一旦启用了`__slots__`特性,默认情况下子类不会继承父类所设定的槽位集合。因此,若希望保持此功能需显式重申或扩展之。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值