python魔术方法之__slots__
2021/8/8 17:06:15
本文主要是介绍python魔术方法之__slots__,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
__slots__作用
1.减少内存消耗
2.限制添加类属性及类初始化参数
实现__slots__
1.限制单个类属性
class Base(object): __slots__ = ['name'] pass B = Base() B.name = 'John'
2.限制多个类属性,在__slots__的列表中继续添加即可
class Base(object): __slots__ = ['name','age'] pass B = Base() B.name = 'John' B.age = 18
当添加类属性为非__slots__列表中的参数,会报错 AttributeError: 'Base' object has no attribute 'name1'
class Base(object): __slots__ = ['name'] pass B = Base() B.name1 = 'John' #AttributeError: 'Base' object has no attribute 'name1'
同样,__slots__会限制类初始化参数
class Base(object): __slots__ = ['name'] def __init__(self,name,age): self.name = name self.age = age pass B = Base('John',18) #AttributeError: 'Base' object has no attribute 'age'
节约内存
由于默认情况下每个类都会有一个dict,通过__dict__访问,这个dict维护了这个实例的所有属性。如果类中使用__slots__时,该对象不会自动产生__dict__属性
class Base(object): __slots__ = ['name'] def __init__(self,name): self.name = name pass B = Base('John') print(B.__dict__) #打印报错AttributeError: 'Base' object has no attribute '__dict__' class Base(object): # __slots__ = ['name'] def __init__(self,name): self.name = name pass B = Base('John') print(B.__dict__) # {'name': 'John'}
这篇关于python魔术方法之__slots__的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-03用FastAPI掌握Python异步IO:轻松实现高并发网络请求处理
- 2025-01-02封装学习:Python面向对象编程基础教程
- 2024-12-28Python编程基础教程
- 2024-12-27Python编程入门指南
- 2024-12-27Python编程基础
- 2024-12-27Python编程基础教程
- 2024-12-27Python编程基础指南
- 2024-12-24Python编程入门指南
- 2024-12-24Python编程基础入门
- 2024-12-24Python编程基础:变量与数据类型