3.4.2.4 __slots__
By default, instances of both old and new-style classes have a dictionary
for attribute storage. This wastes space for objects having very few instance
variables. The space consumption can become acute when creating large numbers
of instances.
네이버 사전 발췌
con·sump·tion〔








〕 n.

1 소비(opp. production);소비량[액];【경제】 (재화·서비스의) 소비
a·cute〔




〕 a. (종종 a·cut·er;-est)4 <상황·사태·문제 등이> 중대한, 심각한, 매우 어려운
이전 스타일 클래스나 새로운 스타일 클래스나 속성 정보를 저장하기 위한 사전을 가지고 있습니다. 하지만 멤버 변수가 매우 적은 오브젝트에서 사전을 갖고 있는건 메모리 낭비 입니다. 이러한 공간 소비는 많은 양의 인스턴스를 만들때 심각한 문제가 될 수 있습니다.
The default can be overridden by defining
__slots__ in a new-style class
definition. The
__slots__ declaration takes a sequence of instance
variables and reserves just enough space in each instance to hold a value
for each variable. Space is saved because
__dict__ is not created for
each instance.
새로운 스타일 클래스에서는 기본적으로 __slots__ 를 정의해 오버라이딩할 수 있습니다. __slots__ 선언은 인스턴스 변수 시퀀스와 각 인스턴스별로 각 변수들에 값을 넣어둘
충분한 공간을 준비해둡니다. 각 인스턴스별 사전을 만들지 않으므로 공간을 절약할 수
있습니다.
- __slots__
- This class variable can be assigned a string, iterable, or sequence of
strings with variable names used by instances. If defined in a new-style class,
__slots__ reserves space for the declared variables and prevents the
automatic creation of __dict__ and __weakref__ for each
instance. New in version 2.2.
이 클래스 변수는 문자열이나 이터러블, 인스턴스들이 사용하는 변수명이 들어있는 문자열 시퀀스로 설정될 수 있습니다.
만약 새로운 스타일 클래스를 정의한다면 __slots__ 는 __dict__ 나 __weakref__ 의
생성을 막고 동적으로 선언될 변수들을 위한 공간을 확보합니다.
(2.2 버전부터 추가된 기능입니다. )
Notes on using
__slots____slots__ 를 사용할때 알아두어야 할 사항
- Without a __dict__ variable, instances cannot be assigned new
variables not listed in the __slots__ definition. Attempts to assign
to an unlisted variable name raises AttributeError. If
dynamic assignment of new variables is desired, then add
'__dict__'
to the sequence of strings in the __slots__ declaration. Changed in version 2.3: Previously, adding
'__dict__' to the __slots__ declaration would not enable
the assignment of new attributes not specifically listed in the sequence of
instance variable names.
- __dict__ 가 없으므로 인스턴스들은 __slots__ 에 적혀진 변수외에는 새로운 변수들을 추가로 만들수 없습니다. 만약 __slots__ 에 적혀진 변수를 만들경우에는 AttributeError 가 발생합니다. 만약 변수의 동적 구문이 필요하다면 __slots__ 선언시 문자열 시쿼스안에 __dict__ 를 추가하면 됩니다. (2.3 버전에서 변경된 기능입니다. 이전에는 __slots__ 안에 __dict__ 를 추가하더라도 새로운 속성을 추가하는 것이 불가능했으며 멤버 변수 이름 시퀀스도 특별하게 리스트될수 없었습니다 )
- Without a __weakref__ variable for each instance, classes
defining __slots__ do not support weak references to its instances.
If weak reference support is needed, then add
'__weakref__' to the
sequence of strings in the __slots__ declaration. Changed in version 2.3: Previously, adding
'__weakref__' to the __slots__ declaration would not
enable support for weak references.
- __slots__ are implemented at the class level by creating
descriptors (3.4.2) for each variable
name. As a result, class attributes cannot be used to set default values for
instance variables defined by __slots__; otherwise, the class
attribute would overwrite the descriptor assignment.
- If a class defines a slot also defined in a base class, the instance
variable defined by the base class slot is inaccessible (except by retrieving
its descriptor directly from the base class). This renders the meaning of the
program undefined. In the future, a check may be added to prevent this.
- The action of a __slots__ declaration is limited to the class
where it is defined. As a result, subclasses will have a __dict__
unless they also define __slots__.
- __slots__ do not work for classes derived from
``variable-length'' built-in types such as long, str and tuple.
- Any non-string iterable may be assigned to __slots__. Mappings
may also be used; however, in the future, special meaning may be assigned to the
values corresponding to each key.
예제
>>> class MyDict(dict):
... __slots__ = ["x", "y"]
...
>>> d = MyDict()
>>> d.x = 1
>>> d.y = 2
>>> d.w = 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'MyDict' object has no attribute 'w'
관련 링크:
http://serv.python.or.kr/pykug/_c6_c4_c0_cc_bd_e3_202_2e2_c0_c7_20_bb_f5_b1_e2_b4_c9#line901
만일 외부에서 동적으로 지정된 이름 이외의 인스턴스 변수를 만들 수 없도록 제한하려면 __slots__을 이용한다.
__slots__은 인스턴스 변수를 저장하는 리스트이고, 인스턴스에서 사용될 공간을 확보한다.
__slots__에 등록된 인스턴스 변수만을 사용 가능하게 한다.
http://home.paran.com/johnsonj/etc/%ED%95%9C%EA%B8%80%ED%8C%90PQR232EUCKRPRINT.html
슬롯(Slots). 새로운 스타일의 클래스는 클래스 속성 __slots__을 정의하여 할당가능한(assignable) 속성 이름의 리스트를 제약할 수 있다. 타자실수(typos)를 예방하기 위함. (보통은 파이썬에서 탐지되지 않고 새로운 속성이 생성된다), 예. __slots__
= ('x', 'y')
주의: 최근의 토론에 의하면, 슬롯의 실제 목적은 여전히 불명확해 보이며 (최적화 때문인가?), 아마도 사용을 삼가해야 할 것 같다.

(
0)

(
0)
http://imp17.com/tc/myevan/trackback/23