12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Calling Superclass ConstructorsMethods are normally called through instances. Calls to methods through the class,though, do show up in a variety of special roles. One common scenario involves theconstructor method. The _ _init_ _ method, like all attributes, is looked up by inheritance.This means that at construction time, <strong>Python</strong> locates and calls just one _ _init_ _.If subclass constructors need to guarantee that superclass construction-time logic runs,too, they generally must call the superclass’s _ _init_ _ method explicitly through theclass:class Super:def _ _init_ _(self, x):...default code...class Sub(Super):def _ _init_ _(self, x, y):Super.__init__(self, x)...custom code...# Run superclass _ _init_ _# Do my init actionsI = Sub(1, 2)This is one of the few contexts in which your code is likely to call an operator overloadingmethod directly. Naturally, you should only call the superclass constructorthis way if you really want it to run—without the call, the subclass replaces it completely.For a more realistic illustration of this technique in action, stay tuned for thefinal example in this chapter. *Other Method Call PossibilitiesThis pattern of calling methods through a class is the general basis of extending(instead of completely replacing) inherited method behavior. In Chapter 26, we’llalso meet a new option added in <strong>Python</strong> 2.2, static methods, that allow you to codemethods that do not expect instance objects in their first arguments. Such methodscan act like simple instanceless functions, with names that are local to the classes inwhich they are coded. This is an advanced and optional extension, though; normally,you must always pass an instance to a method, whether it is called through aninstance or a class.InheritanceThe whole point of a namespace tool like the class statement is to support nameinheritance. This section expands on some of the mechanisms and roles of attributeinheritance in <strong>Python</strong>.* On a somewhat related note, you can also code multiple _ _init_ _ methods within the same class, but onlythe last definition will be used; see Chapter 25 for more details.486 | Chapter 24: Class Coding Details

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!