12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

A Third ExampleOn to another example. This time, we’ll define a subclass of SecondClass that implementsthree specially named attributes that <strong>Python</strong> will call automatically: _ _init_ _is called when a new instance object is being constructed (self is the new ThirdClassobject), and _ _add_ _ and _ _mul_ _ are called when a ThirdClass instance appears in a+ or * expression, respectively. Here’s our new subclass:>>> class ThirdClass(SecondClass): # <strong>Is</strong> a SecondClass... def _ _init_ _(self, value): # On "ThirdClass(value)"... self.data = value... def _ _add_ _(self, other): # On "self + other"... return ThirdClass(self.data + other)... def _ _mul_ _(self, other):... self.data = self.data * other # On "self * other"...>>> a = ThirdClass("abc") # New _ _init_ _ called>>> a.display( ) # Inherited methodCurrent value = "abc">>> b = a + 'xyz' # New _ _add_ _: makes a new instance>>> b.display( )Current value = "abcxyz">>> a * 3 # New _ _mul_ _: changes instance in-place>>> a.display( )Current value = "abcabcabc"ThirdClass “is a” SecondClass, so its instances inherit the display method fromSecondClass. But, ThirdClass generation calls pass an argument now (e.g., “abc”); it’spassed to the value argument in the _ _init_ _ constructor and assigned to self.datathere. Further, ThirdClass objects can show up in + and * expressions; <strong>Python</strong> passesthe instance object on the left to the self argument, and the value on the right toother, as illustrated in Figure 23-3.a * 3_mul_(self, other)Figure 23-3. In operator overloading, expression operators and other built-on operationsperformed on class instances are mapped back to specially named methods in the class. Thesespecial methods are optional, and may be inherited as usual. Here, a “*” expression triggersthe “_mul_” method.474 | Chapter 23: Class Coding Basics

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

Saved successfully!

Ooh no, something went wrong!