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.

% python>>> from adder import *>>> x = Adder( )>>> x.add(1, 2)not implemented!>>> x = ListAdder( )>>> x.add([1], [2])[1, 2]>>> x = DictAdder( )>>> x.add({1:1}, {2:2}){1: 1, 2: 2}>>> x = Adder([1])>>> x + [2]not implemented!>>>>>> x = ListAdder([1])>>> x + [2][1, 2]>>> [2] + xTraceback (innermost last):File "", line 1, in ?TypeError: _ _add_ _ nor _ _radd_ _ defined for these operandsNotice in the last test that you get an error for expressions where a class instanceappears on the right of a +; if you want to fix this, use _ _radd_ _ methods, asdescribed in “Operator Overloading” in Chapter 24.If you are saving a value in the instance anyhow, you might as well rewrite theadd method to take just one argument, in the spirit of other examples in Part VI:class Adder:def _ _init_ _(self, start=[]):self.data = startdef _ _add_ _(self, other):return self.add(other)def add(self, y):print 'not implemented!'class ListAdder(Adder):def add(self, y):return self.data + y# Pass a single argument# The left side is in selfclass DictAdder(Adder):def add(self, y):pass# Change me to use self.data instead of xx = ListAdder([1, 2 ,3])y = x + [4, 5, 6]print y # Prints [1, 2, 3, 4, 5, 6]Because values are attached to objects rather than passed around, this version isarguably more object-oriented. And, once you’ve gotten to this point, you’llprobably find that you can get rid of add altogether, and simply define typespecific_ _add_ _ methods in the two subclasses.Part VI, Classes and OOP | 665

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

Saved successfully!

Ooh no, something went wrong!