Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Object-oriented Python

You're reading from   Mastering Object-oriented Python If you want to master object-oriented Python programming this book is a must-have. With 750 code samples and a relaxed tutorial, it's a seamless route to programming Python.

Arrow left icon
Product type Paperback
Published in Apr 2014
Publisher Packt
ISBN-13 9781783280971
Length 634 pages
Edition Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Steven F. Lott Steven F. Lott
Author Profile Icon Steven F. Lott
Steven F. Lott
Arrow right icon
View More author details
Toc

Table of Contents (26) Chapters Close

Mastering Object-oriented Python
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Some Preliminaries
1. The __init__() Method FREE CHAPTER 2. Integrating Seamlessly with Python Basic Special Methods 3. Attribute Access, Properties, and Descriptors 4. The ABCs of Consistent Design 5. Using Callables and Contexts 6. Creating Containers and Collections 7. Creating Numbers 8. Decorators and Mixins – Cross-cutting Aspects 9. Serializing and Saving – JSON, YAML, Pickle, CSV, and XML 10. Storing and Retrieving Objects via Shelve 11. Storing and Retrieving Objects via SQLite 12. Transmitting and Sharing Objects 13. Configuration Files and Persistence 14. The Logging and Warning Modules 15. Designing for Testability 16. Coping With the Command Line 17. The Module and Package Design 18. Quality and Documentation Index

The base class object __init__() method


Fundamental to the life cycle of an object are its creation, initialization, and destruction. We'll defer creation and destruction to a later chapter on more advanced special methods and only focus on initialization for now.

The superclass of all classes, object, has a default implementation of __init__() that amounts to pass. We aren't required to implement __init__(). If we don't implement it, then no instance variables will be created when the object is created. In some cases, this default behavior is acceptable.

We can always add attributes to an object that's a subclass of the foundational base class, object. Consider the following class that requires two instance variables but doesn't initialize them:

class Rectangle:
    def area( self ):
        return self.length * self.width

The Rectangle class has a method that uses two attributes to return a value. The attributes have not been initialized anywhere. This is legal Python. It's a little strange to avoid specifically setting attributes, but it's valid.

The following is an interaction with the Rectangle class:

>>> r= Rectangle()
>>> r.length, r.width = 13, 8
>>> r.area()
104

While this is legal, it's a potential source of deep confusion, which is a good reason to avoid it.

However, this kind of design grants flexibility, so there could be times when we needn't set all of the attributes in the __init__() method. We walk a fine line here. An optional attribute is a kind of subclass that's not formally declared as a proper subclass. We're creating polymorphism in a way that could lead to confusing and inappropriate use of convoluted if statements. While uninitialized attributes may be useful, they could be the symptom of a bad design.

The Zen of Python poem (import this) offers the following advice:

"Explicit is better than implicit."

An __init__() method should make the instance variables explicit.

Tip

Pretty Poor Polymorphism

There's a fine line between flexibility and foolishness.

We may have stepped over the edge off flexible into foolish as soon as we feel the need to write:

if 'x' in self.__dict__:

Or:

try:
    self.x
except AttributeError:

It's time to reconsider the API and add a common method or attribute. Refactoring is better than adding if statements.

You have been reading a chapter from
Mastering Object-oriented Python
Published in: Apr 2014
Publisher: Packt
ISBN-13: 9781783280971
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime