#超詳細#Pythonの「__slots__」詳細プロパティ

1はじめに

Pythonは__dict__に、一般的なクラス、属性が任意のクラスのインスタンスに割り当てることができ、動的言語であるが、より大きなフットプリントを格納するデータ辞書(ハッシュ)は、これらの属性を格納する、効率が悪く、__特性slots__上記の問題を解決するために表示されます。
__slots__役割を宣言し、クラスメンバのプロパティを定義し、__dict__を作成することを拒否することであり、__weakref__クラスは、メモリ空間を節約するための属性。

2.使用方法

>>> class Student(object):
...     __slots__ = ('name', 'age')
...     
>>> Abey = Student()
>>> Abey.name = 'Abey'
>>> Abey.gender = 'Female'
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'gender'
>>> Abey.__dict__
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'Student' object has no attribute '__dict__'

3継承ツリーの問題

二つの形式で連続して__slots__:

  1. __slots__ないサブクラスは、親クラスが継承__slots__は、つまり、この時点で自由にサブクラスにインスタンスの属性を割り当てることができていないと宣言しました
  2. 、つまり、独自のサブクラス__slots__ + __slots__親クラスのために、この時間を親クラスの__slots__を継承する場合、サブクラスの宣言__slots__、
    次の例の親クラスに:

参照

  1. 公式Pythonドキュメント。
  2. 使い方スロット?、アーロン・ホール、スタックオーバーフロー
公開された59元の記事 ウォンの賞賛2 ビュー4671

おすすめ

転載: blog.csdn.net/lch551218/article/details/104552245