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.

Note that it’s important to copy the start value by appending instead of slicinghere because otherwise the result may not be a true list, and so will not respondto expected list methods, such as append (e.g., slicing a string returns anotherstring, not a list). You would be able to copy a MyList start value by slicingbecause its class overloads the slicing operation, and provides the expected listinterface; however, you need to avoid slice-based copying for objects such asstrings. Also, note that sets are a built-in type in <strong>Python</strong> today, so this is largelyjust a coding exercise (see Chapter 5 for more on sets).3. Subclassing. My solution (mysub.py) appears below. Your solution should besimilar:from mylist import MyListclass MyListSub(MyList):calls = 0def _ _init_ _(self, start):self.adds = 0MyList._ _init_ _(self, start)def _ _add_ _(self, other):MyListSub.calls = MyListSub.calls + 1self.adds = self.adds + 1return MyList._ _add_ _(self, other)def stats(self):return self.calls, self.adds# Shared by instances# Varies in each instance# Class-wide counter# Per-instance counts# All adds, my addsif __name__ == '_ _main_ _':x = MyListSub('spam')y = MyListSub('foo')print x[2]print x[1:]print x + ['eggs']print x + ['toast']print y + ['bar']print x.stats( )% python mysub.pya['p', 'a', 'm']['s', 'p', 'a', 'm', 'eggs']['s', 'p', 'a', 'm', 'toast']['f', 'o', 'o', 'bar'](3, 2)4. Metaclass methods. I worked through this exercise as follows. Notice that operatorstry to fetch attributes through _ _getattr_ _, too; you need to return a valueto make them work:>>> class Meta:... def _ _getattr_ _(self, name):... print 'get', namePart VI, Classes and OOP | 667

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

Saved successfully!

Ooh no, something went wrong!