Book Image

Learning Python Design Patterns - Second Edition - Second Edition

By : Chetan Giridhar, Gennadiy Zlobin
Book Image

Learning Python Design Patterns - Second Edition - Second Edition

By: Chetan Giridhar, Gennadiy Zlobin

Overview of this book

With the increasing focus on optimized software architecture and design it is important that software architects think about optimizations in object creation, code structure, and interaction between objects at the architecture or design level. This makes sure that the cost of software maintenance is low and code can be easily reused or is adaptable to change. The key to this is reusability and low maintenance in design patterns. Building on the success of the previous edition, Learning Python Design Patterns, Second Edition will help you implement real-world scenarios with Python’s latest release, Python v3.5. We start by introducing design patterns from the Python perspective. As you progress through the book, you will learn about Singleton patterns, Factory patterns, and Façade patterns in detail. After this, we’ll look at how to control object access with proxy patterns. It also covers observer patterns, command patterns, and compound patterns. By the end of the book, you will have enhanced your professional abilities in software architecture, design, and development.
Table of Contents (19 chapters)
Learning Python Design Patterns Second Edition
Credits
Foreword
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Singletons and metaclasses


Let's start with a brief introduction to metaclasses. A metaclass is a class of a class, which means that the class is an instance of its metaclass. With metaclasses, programmers get an opportunity to create classes of their own type from the predefined Python classes. For instance, if you have an object, MyClass, you can create a metaclass, MyKls, that redefines the behavior of MyClass to the way that you need. Let's understand them in detail.

In Python, everything is an object. If we say a=5, then type(a) returns <type 'int'>, which means a is of the int type. However, type(int) returns <type 'type'>, which suggests the presence of a metaclass as int is a class of the type type.

The definition of class is decided by its metaclass, so when we create a class with class A, Python creates it by A = type(name, bases, dict):

  • name: This is the name of the class

  • base: This is the base class

  • dict: This is the attribute variable

Now, if a class has a predefined...