Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 7b30c2b

Browse filesBrowse files
committed
__slots__
1 parent 692c4af commit 7b30c2b
Copy full SHA for 7b30c2b

File tree

Expand file treeCollapse file tree

1 file changed

+27
-25
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+27
-25
lines changed

‎README.md

Copy file name to clipboardExpand all lines: README.md
+27-25Lines changed: 27 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -493,38 +493,40 @@ size, color, disposition = cat
493493
<b><a href="#">↥ back to top</a></b>
494494
</div>
495495

496-
## Q. What is `__slots__` and when is it useful?
497-
Normally, all class objects have an `__dict__` which allows new attributes to be bound to a class instance at runtime. When a class is defined with `__slots__`, only attributes whose names are present in the `__slots__` sequence are allowed.
498-
This results in instances of this class not having an `__dict__` attribute and not being able to bind new attributes at run time.`__slots__` is useful because it eliminates
496+
## Q. What is `__slots__` and when is it useful?
499497

500-
`__slots__` allow us to explicitly declare data members (like properties) and deny the creation of `__dict__` and `__weakref__` (unless explicitly declared in __slots__ or available in a parent.)
498+
In Python, every class can have instance attributes. By default Python uses a `dict` to store an object\'s instance attributes. This is really helpful as it allows setting arbitrary new attributes at runtime.
501499

502-
The space saved over using `__dict__` can be significant.
503-
504-
object.__slots__
505-
506-
This class variable can be assigned a string, iterable, or sequence of strings with variable names used by instances. `__slots__` reserves space for the declared variables and prevents the automatic creation of `__dict__` and `__weakref__` for each instance.
507-
508-
3.3.2.4.1. Notes on using `__slots__`
509-
•When inheriting from a class without `__slots__`, the __dict__ and __weakref__ attribute of the instances will always be accessible.
510-
511-
•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.
500+
However, for small classes with known attributes it might be a bottleneck. The `dict` wastes a lot of RAM. Python can\'t just allocate a static amount of memory at object creation to store all the attributes. Therefore it sucks a lot of RAM if you create a lot of objects. The usage of `__slots__` to tell Python not to use a dict, and only allocate space for a fixed set of attributes.
512501

513-
•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.
502+
*Example:*
514503

515-
__slots__ are implemented at the class level by creating descriptors (Implementing Descriptors) 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.
504+
**1. Object without slots**
516505

517-
•The action of a __slots__ declaration is not limited to the class where it is defined. __slots__ declared in parents are available in child classes. However, child subclasses will get a __dict__ and __weakref__ unless they also define __slots__ (which should only contain names of any additional slots).
518-
519-
•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.
520-
521-
•Nonempty __slots__ does not work for classes derived from "variable-length" built-in types such as int, bytes and tuple.
522-
523-
•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.
506+
```py
507+
class MyClass(object):
508+
def __init__(self, *args, **kwargs):
509+
self.a = 1
510+
self.b = 2
511+
512+
if __name__ == "__main__":
513+
instance = MyClass()
514+
print(instance.__dict__)
515+
```
524516

525-
__class__ assignment works only if both classes have the same __slots__.
517+
**2. object with slots**
526518

527-
•Multiple inheritance with multiple slotted parent classes can be used, but only one parent is allowed to have attributes created by slots (the other bases must have empty slot layouts) - violations raise TypeError.
519+
```py
520+
class MyClass(object):
521+
__slots__=['a', 'b']
522+
def __init__(self, *args, **kwargs):
523+
self.a = 1
524+
self.b = 2
525+
526+
if __name__ == "__main__":
527+
instance = MyClass()
528+
print(instance.__slots__)
529+
```
528530

529531
<div align="right">
530532
<b><a href="#">↥ back to top</a></b>

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.