0% found this document useful (0 votes)
4 views

Python Tutorial_ Slots, Avoiding Dynamically Created Attributes

The document discusses the concept of 'slots' in Python, which are used to prevent the dynamic creation of attributes in class instances, thereby reducing memory consumption. It explains how to define slots using the __slots__ attribute and provides examples of their usage. Additionally, it notes that with Python 3.3, the memory efficiency of slots has been somewhat diminished due to the introduction of key-sharing dictionaries.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Tutorial_ Slots, Avoiding Dynamically Created Attributes

The document discusses the concept of 'slots' in Python, which are used to prevent the dynamic creation of attributes in class instances, thereby reducing memory consumption. It explains how to define slots using the __slots__ attribute and provides examples of their usage. Additionally, it notes that with Python 3.3, the memory efficiency of slots has been somewhat diminished due to the introduction of key-sharing dictionaries.

Uploaded by

Sentinel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Python Course

Home Python 2 Tutorial Python 3 Tutorial Advanced Topics Numerical Programming Machine Learning Tkinter Tutorial Contact

Previous Chapter: OOP, Inheritance Example


Next Chapter: Classes and Class Creation

Slots

Follow Bernd Klein,


the author of this
Avoiding Dynamically Created Attributes website, at Google+:
Bernd Klein on
Python 3 The attributes of objects are stored in a dictionary "__dict__". Like any other dictionary, a dictionary used for attribute storage doesn't have a fixed number of
Google
Tutorial elements. In other words, you can add elements to dictionaries after they have been defined, as we have seen in our chapter on dictionaries. This is the reason, why
Bernd Klein on
you can dynamically add attributes to objects of classes that we have created so far:
The Origins of Facebook
Python >>> class A(object):
Starting with ... pass
... Search this website:
Python: The >>> a = A()
Interactive Shell >>> a.x = 66
Go
Executing a >>> a.y = "dynamically created attribute"
Script
The dictionary containing the attributes of "a" can be accessed like this: This topic in German
Indentation / Deutsche
Data Types and >>> a.__dict__ Übersetzung: Slots,
Variables {'y': 'dynamically created attribute', 'x': 66} Vermeidung von
Operators dynamisch erzeugten
Sequential Data You might have wondered that you can dynamically add attributes to the classes, we have defined so far, but that you can't do this with built-in classes like 'int', or Attributen
'list':
Types: Lists and
Strings >>> x = 42 Python 3
List >>> x.a = "not possible to do it"
Manipulations Traceback (most recent call last): This is a tutorial in
File "<stdin>", line 1, in <module> Python3, but this
Shallow and AttributeError: 'int' object has no attribute 'a'
chapter of our course
Deep Copy >>>
>>> lst = [34, 999, 1001] is available in a
Dictionaries
>>> lst.a = "forget it" version for Python
Sets and Frozen 2.x as well: Slots,
Traceback (most recent call last):
Sets File "<stdin>", line 1, in <module> Avoiding Dynamically
An Extensive AttributeError: 'list' object has no attribute 'a' Created Attributes in
Example Using Python 2.x
Sets Using a dictionary for attribute storage is very convenient, but it can mean a waste of space for objects, which have only a small amount of instance variables. The
space consumption can become critical when creating large numbers of instances. Slots are a nice way to work around this space consumption problem. Instead of having a dynamic dict that allows adding
input via the Classroom
attributes to objects dynamically, slots provide a static structure which prohibits additions after the creation of an instance.
keyboard Training
Conditional Courses
When we design a class, we can use slots to prevent the dynamic creation of attributes. To define slots, you have to define a list with the name __slots__. The list has to contain all the attributes, you want to use.
Statements We demonstrate this in the following class, in which the slots list contains only the name for an attribute "val".
Loops, while The goal of this
Loop class S(object): website is to provide
educational material,
For Loops __slots__ = ['val'] allowing you to learn
Difference
Python on your own.
between def __init__(self, v):
Nevertheless, it is
interators und self.val = v
faster and more
Iterables efficient to attend a
Output with Print x = S(42) "real" Python course
Formatted output print(x.val) in a classroom, with
with string an experienced
x.new = "not possible" trainer. So why not
modulo and the
attend one of the live
format method If we start this program, we can see, that it is not possible to create dynamically a new attribute. We fail to create an attribute "new": Python courses in
Functions
42 Strasbourg, Paris,
Recursion and Luxembourg,
Traceback (most recent call last):
Recursive File "slots_ex.py", line 12, in <module> Amsterdam, Zürich /
Functions x.new = "not possible" Zurich, Vienna /
Parameter AttributeError: 'S' object has no attribute 'new' Wien, London, Berlin,
Passing in Munich, Hamburg,
Functions We mentioned in the beginning that slots are preventing a waste of space with objects. Since Python 3.3 this advantage is not as impressive any more. With Python 3.3 Key-Sharing Dictionaries are used for the Frankfurt, Stuttgart,
storage of objects. The attributes of the instances are capable of sharing part of their internal storage between each other, i.e. the part which stores the keys and their corresponding hashes. This helps to reduce or Lake Constance by
Namespaces
the memory consumption of programs, which create many instances of non-builtin types. Bernd Klein, the
Global and Local
Previous Chapter: OOP, Inheritance Example author of this
Variables tutorial?
Next Chapter: Classes and Class Creation
Decorators
Memoization with You can book on-site
Decorators classes at your
Read and Write company or
Files organization, e.g. in
Modular England, Switzerland,
Austria, Germany,
Programming
France, Belgium, the
and Modules
Netherlands,
Packages in Luxembourg, Poland,
Python UK, Italy and other
Regular locations in Europe
Expressions and in Canada.
Regular
Expressions, We had courses in
the following cities:
Advanced
Amsterdam (The
Lambda
Netherlands), Berlin
Operator, Filter, (Germany), Bern
Reduce and Map (Switzerland), Basel
List (Switzerland), Zurich
Comprehension (Switzerland),
Iterators and Locarno
Generators (Switzerland), Den
Exception Haag (The Hague),
Hamburg, Toronto
Handling
(Canada), Edmonton
Tests, DocTests,
(Canada), Munich
UnitTests (Germany) and many
Object Oriented other cities.
Programming
Class and Contact us so we can
Instance define and find the
Attributes best course
curriculum to meet
Properties vs.
your needs, and
getters and
schedule course
setters sessions to be held at
Inheritance your location.
Multiple
Inheritance
Magic Methods Skilled Python
and Operator Programmers
Overloading
OOP, Inheritance You are looking for
Example experienced Python
Slots developers or
programmers? We
Classes and
can help you, please
Class Creation
contact us.
Road to
Metaclasses
Quote of the
Metaclasses
Day:
Metaclass Use
Case: Count "Any program is only
Function Calls as good as it is
Abstract Classes useful." (Linus
Torvalds)

Definition of
Slots Data Protection
Declaration

Data Protection
Generally, slots are
Declaration
narrow opening, like
a groove or a slit: for
example, a slot to
input coins in a
vending machine or a
mail slot.

A slot can also be an


assigned place in a
schedule or a
sequence: the time
slot for a meeting or
a TV program.

Slots are known as


slot machines as
well.

In computers the
term "slot" is used
for expansion slots.
An expansion slot is
an opening located
inside a computer on
the motherboard or
riser board that
allows additional
boards to be
connected.

This website is
supported by:

Linux and Python


Courses and
Seminars

© 2011 - 2018, Bernd Klein, Bodenseo; Design by Denise Mitchinson adapted for python-course.eu by Bernd Klein

You might also like