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.

def delegate(self):self.action( )def action(self):assert 0, 'action must be defined!'We’ll meet assert in Chapter 27; in short, if its expression evaluates to false, it raisesan exception with an error message. Here, the expression is always false (0) soastotrigger an error message if a method is not redefined, and inheritance locates the versionhere. Alternatively, some classes simply raise a NotImplemented exceptiondirectly in such method stubs. We’ll study the raise statement in Chapter 27.For a somewhat more realistic example of this section’s concepts in action, see exercise8 at the end of Chapter 26, and its solution in “Part VI, Classes and OOP” (inAppendix B). Such taxonomies are a traditional way to introduce OOP, but they’re abit removed from most developers’ job descriptions.Operator OverloadingWe looked briefly at operator overloading in the prior chapter; here, we’ll fill in moredetails, and look at a few commonly used overloading methods. Here’s a review ofthe key ideas behind overloading:• Operator overloading lets classes intercept normal <strong>Python</strong> operations.• Classes can overload all <strong>Python</strong> expression operators.• Classes can also overload operations such as printing, function calls, attributequalifications, etc.• Overloading makes class instances act more like built-in types.• Overloading is implemented by providing specially named class methods.Let’s look at a simple example of overloading at work. If certain specially namedmethods are provided in a class, <strong>Python</strong> automatically calls them when instances ofthe class appear in expressions related to the associated operations. For instance, theNumber class in the following file, number.py, provides a method to intercept instanceconstruction (_ _init_ _), as well as one for catching subtraction expressions (_ _sub_ _).Special methods such as these are the hooks that let you tie into built-in operations:class Number:def _ _init_ _(self, start):self.data = startdef _ _sub_ _(self, other):return Number(self.data - other)# On Number(start)# On instance - other# Result is a new instance>>> from number import Number # Fetch class from module>>> X = Number(5) # Number._ _init_ _(X, 5)>>> Y = X - 2 # Number._ _sub_ _(X, 2)>>> Y.data # Y is new Number instance3Operator Overloading | 491

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

Saved successfully!

Ooh no, something went wrong!