Skip to Content
Clean Code in Python
book

Clean Code in Python

by Mariano Anaya
August 2018
Intermediate to advanced
332 pages
9h 12m
English
Packt Publishing
Content preview from Clean Code in Python

Slots

When a class defines the __slots__ attribute, it can contain all the attributes that the class expects and no more.

Trying to add extra attributes dynamically to a class that defines __slots __ will result in an AttributeError. By defining this attribute, the class becomes static, so it will not have a __dict__ attribute where you can add more objects dynamically.

How, then, are its attributes retrieved if not from the dictionary of the object? By using descriptors. Each name defined in a slot will have its own descriptor that will store the value for retrieval later:

class Coordinate2D:    __slots__ = ("lat", "long")    def __init__(self, lat, long):        self.lat = lat        self.long = long    def __repr__(self): return f"{self.__class__.__name__}({self.lat}, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Clean Code in Python - Second Edition

Clean Code in Python - Second Edition

Mariano Anaya
Python for Programmers

Python for Programmers

Paul Deitel, Harvey Deitel

Publisher Resources

ISBN: 9781788835831Supplemental Content