Python - __slots__魔法方法

Python中默认用一个字典来保存一个对象的实例属性,使得我们在运行时可以任意设置新属性。

但是,对于已知固有属性的小型类来说,这个字典浪费了很多内存。(由于可设置新属性,Python不能在对象创建时直接分配一个固定量的内存保存所有属性)

因此,如果创建成千上万个这样的小类,Python就会浪费掉很多内存。

此时,引入类中的__slots__方法,使得python

  • 给类指定一个固定大小的空间存放属性
  • 无法给该类创建的实例添加新的属性

例子:

  • 不使用__slots__
    class Point_1(object):
    	def __init__(self, x=0, y=0):
    		self.x = x
    		self.y = y
    	# ...
    
  • 使用__slots__
    class Point_2(object):
    	__slots__ = ['x', 'y']
    	def __init__(self, x=0, y=0):
    		self.x = x
    		self.y = y
    	# ...
    
    # 创建 Point_1 类的实例 p1
    In [10]: p1 = Point_1()
    # 可以给 p1 添加新的属性 z
    In [11]: p1.z = 0 
    
    # 创建 Point_2 类的实例 p2
    In [12]: p2 = Point_2()
    # 无法给 p2 添加新的属性
    In [13]: p2.z
    ---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-19-b152092c7c5d> in <module>()
    ----> 1 p2.z
    
    

猜你喜欢

转载自blog.csdn.net/weixin_39129504/article/details/86380885