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.

2. Operator overloading. The solution code (file mylist.py) uses a few operatoroverloading methods that the text didn’t say much about, but they should bestraightforward to understand. Copying the initial value in the constructor isimportant because it may be mutable; you don’t want to change or have areference to an object that’s possibly shared somewhere outside the class. The_ _getattr_ _ method routes calls to the wrapped list. For hints on an easierway to code this in <strong>Python</strong> 2.2 and later, see “Extending Types by Subclassing”in Chapter 26:class MyList:def _ _init_ _(self, start):#self.wrapped = start[:] # Copy start: no side effectsself.wrapped = []# Make sure it's a list herefor x in start: self.wrapped.append(x)def _ _add_ _(self, other):return MyList(self.wrapped + other)def _ _mul_ _(self, time):return MyList(self.wrapped * time)def _ _getitem_ _(self, offset):return self.wrapped[offset]def _ _len_ _(self):return len(self.wrapped)def _ _getslice_ _(self, low, high):return MyList(self.wrapped[low:high])def append(self, node):self.wrapped.append(node)def _ _getattr_ _(self, name): # Other members: sort/reverse/etcreturn getattr(self.wrapped, name)def _ _repr_ _(self):return repr(self.wrapped)if _ _name_ _ == '_ _main_ _':x = MyList('spam')print xprint x[2]print x[1:]print x + ['eggs']print x * 3x.append('a')x.sort( )for c in x: print c,% python mylist.py['s', 'p', 'a', 'm']a['p', 'a', 'm']['s', 'p', 'a', 'm', 'eggs']['s', 'p', 'a', 'm', 's', 'p', 'a', 'm', 's', 'p', 'a', 'm']a a m p s666 | Appendix B: Solutions to End-of-Part Exercises

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

Saved successfully!

Ooh no, something went wrong!