My Books‎ > ‎Software Engineering‎ > ‎

Python-Essential Reference



Chapter 7 Classes and Object-Oriented Programming

 

 

The class Statement

 

It’s important to note that a class statement doesn’t create any instances of a class (for example, no accounts are actually created in the preceding example). Rather, a class defines a set of attributes shared by all the instances that will be created later. In this sense, you might think of it as a blueprint that is used to construct instances of an object.

 

Class Instances

 

Instances of a class are created by calling a class object as a function. This first creates a new instance by calling the static method __new__(), which is rarely defined by the user, but implemented as part of object. This, in turn, calls the __init__() method of the class, which is almost always defined by a user to initialize the contents of an instance.

 

Internally, instances are implemented using a dictionary that’s accessible as the instance’s __dict__ attribute. This dictionary contains the information that’s unique to each instance. For example:

 

>>> print a.__dict__

{‘balance’: 1100.0, ‘name’: ‘Guido’}

 

Whenever an attribute name is accessed, the interpreter calls a special method, __getattribute__(self,name).The default

behavior of __getattribute__() is to look for a match in the instance dictionary.  If no match is found, the interpreter searches the dictionary of the class object used to create the instance. If this fails, a search of base classes is performed. If this fails, a final attempt to find the attribute is made by trying to invoke the __getattr__() method of the class (if defined). If this fails, an AttributeError exception is raised.

 

 

Reference Counting and Instance Destruction

 

All instances have a reference count. If the reference count reaches zero, the instance is destroyed. When the instance is about to be destroyed, the interpreter looks for a __del__() method associated with the object and calls it. In practice, it’s rarely necessary for a class to define a __del__() method.

 

 

Inheritance

 

Inheritance is a mechanism for creating a new class that specializes or modifies the behavior of an existing class.The original class is called a base class or a superclass. The new class is called a derived class or a subclass.

 

Python provides a function, super(class,obj), that can be used to call methods in a superclass. This function is most useful if you want to invoke a method in one of the parent classes without having to reimplement Python’s method resolution algorithm.

 

 

Polymorphism

 

Polymorphism, or dynamic binding, is the ability to use an instance without regard for its type. It is handled entirely through the attribute lookup process described for inheritance in the preceding section. Whenever a method is accessed as obj.method(), method is located by searching within the instance itself, the instance’s class definition, and then base classes, in that order. The first match found is used as the method.

 

Information Hiding

 

By default, all attributes are “public.”This means that all attributes of a class instance are accessible without any restrictions. It also implies that everything defined in a base class is inherited and accessible within a derived class.This behavior is often undesirable in object-oriented applications because it exposes the internal implementation of an object and can lead to namespace conflicts between objects defined in a derived class and those defined in a base class.

 

Operator Overloading

 

 

 

 

 

 

Types and Class Membership Tests

 

 

When you create an instance of a class, the type of that instance is the class itself.To test for membership in a class, use the built-in function isinstance(obj,cname).This function returns True if an object, obj, belongs to the class cname or any class derived from cname.

 

Classic Classes

 

A classic class is defined whenever a class does not inherit (directly or indirectly) from object.

 

Metaclasses

 

http://www.ibm.com/developerworks/linux/library/l-pymeta.html (consult as well)

 

When you define a class in Python, the class definition itself becomes an object. For example:

 

class Foo(object): pass

isinstance(Foo,object) # Returns True

 

If you think about this long enough, you will realize that something had to create the Foo object. This creation of the class object is controlled by a special kind of object called a metaclass. Simply stated, a metaclass is an object that knows how to create and manage classes.

 

In the preceding example, the metaclass that is controlling the creation of Foo is a class called type. In fact, if you display the type of Foo, you will find out that it is a type:

 

>>> print type(Foo)

<type ‘type’>

 

When a new class is defined with the class statement, a number of things happen.

  1. the body of the class is executed as series of statements within its own private dictionary, d.
  2. the name of the class, the list of base classes, and the dictionary d are passed to the constructor of a metaclass to create the corresponding class object.

 

Here is an example of how it works:

 

class_name = “Foo”        # Name of class

class_parents = (object,) # Base classes

class_body = “””          # Class body

def __init__(self,x):

self.x = x

def blah(self):

print “Hello World”

“””

class_dict = { }

 

# Execute the body in the local dictionary class_dict

exec class_body in globals(), class_dict

 

# Create the class object Foo

Foo = type(class_name,class_parents,class_dict)

 

This procedure creates a modern class.

 

In the final step of defining a class, the class statement must choose an appropriate metaclass that will be used to create the class object. This choice is controlled in a number of ways:

  1. the class dictionary d is examined for the existence of a __metaclass__ attribute
  2. the class statement examines the first entry in the tuple of base classes (if any)
  3. If no base classes are specified, the class statement checks for the existence of a global variable called __metaclass__

 

 

 



Chapter 8 - Modules and Packages

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 



Chapter 19 - Operating System Services

 

logging

 

The logging module provides a flexible facility for applications to log events, errors, warnings, and debugging information. This information can be collected, filtered, written to files, sent to the system log, and even sent over the network to remote machines.

 

Five different levels of information are collected by the logging module. These levels have both a symbolic name and a numerical value that is used for filtering:

 

Level

Value

Description

CRITICAL

50

Critical errors/messages

ERROR

40

Errors

WARNING

30

Warning messages

INFO

20

Informative messages

DEBUG

10

Debugging

NOTSET

0

No level set