Python類の魔法の方法の_slots__


クラスでオブジェクトをインスタンス化するたびに、オブジェクトのすべてのインスタンス属性を保存する辞書が生成されます.これは、新しい属性を任意に設定するのに非常に役立ちます.
オブジェクトpythonをインスタンス化するたびに、プロパティを保存するために固定サイズのメモリの辞書が割り当てられます.オブジェクトが多い場合、メモリ領域が浪費されます.__slots__の方法でpythonに辞書を使用しないで、固定セットの属性に空間を割り当てることができます.
class Foo(object):
    __slots__ = ("x","y","z")

    def __init__(self,x,y):
        self.x = x
        self.y = y
        self.z = None

    def tell_info(self,name):
      return  getattr(self,name)

c = Foo(10,20)
#      __slots__           
print(c.tell_info("x"))      #   :10

c.z=50
print(c.tell_info("z"))  #   :50

#       __slots__      ,   
c.e = 70    # AttributeError: 'Foo' object has no attribute 'e'

#     .__dict__       
print(c.__dict__) # AttributeError: 'Foo' object has no attribute '__dict__'