Python __slots__使用

问题:

           Python中如何限制class属性

方案:

           Python中可以通过__slots__变量来限制class属性

使用方式:

class Person:
    __slots__ = ['name', 'age']


class Student(Person):
    pass


class Doctor(Person):
    __slots__ = []

如上,当Person通过__slots__限制属性只能为name和age后,Person实例则不能再绑定其他属性。

if __name__ == '__main__':
    person = Person()
    student = Student()
    doctor = Doctor()

    person.sex = 'male'
    student.sex = 'male'
    doctor.sex = 'male'
  1. person绑定sex属性时,执行代码报错:AttributeError: 'Person' object has no attribute 'sex'
  2. student绑定sex属性时,代码执行正常,因为__slots__定义的属性只对当前类有效,对继承的子类无效
  3. 如果继承的子类也定义了__slots__,则子类允许定义的属性就是自身的__slots__加上父类的__slots__,因此 doctor.sex='male'执行报错:AttributeError: 'Doctor' object has no attribute 'sex'
### 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__`特性,默认情况下子类不会继承父类所设定的槽位集合。因此,若希望保持此功能需显式重申或扩展之。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值