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.

x.intersect([1,2,3], [2,3,4], [1,2,3]) # Four operandsSet:[2, 3]>>> x.union(range(10)) # NonmultiSets work, tooSet:[1, 2, 3, 4, 0, 5, 6, 7, 8, 9]6. Class tree links. Here is the way I changed the Lister class, and a rerun of thetest to show its format. To display inherited class attributes, too, you’d need todo something like what the attrnames method currently does, but recursively, ateach class reached by climbing _ _bases_ _ links. Because dir includes inheritedattributes in <strong>Python</strong> 2.2, you might also simply loop through its result: say for xin dir(self) and use getattr(self,x). This won’t directly help, though, if youwish to represent the class tree’s structure in your display (as in the classtree.pyexample in Chapter 24):class Lister:def _ _repr_ _(self):return ("" %(self._ _class_ _._ _name_ _, # My class’s nameself.supers( ),# My class’s supersid(self),# My addressself.attrnames( )) )# name=value listdef attrnames(self):...unchanged...def supers(self):result = ""first = 1for super in self.__class__._ _bases_ _:# One level up from classif not first:result = result + ", "first = 0result = result + super._ _name_ _# name, not repr(super)return resultC:\python\examples> python testmixin.py7. Composition. My solution is below (file lunch.py), with comments from thedescription mixed in with the code. This is one case where it’s probably easier toexpress a problem in <strong>Python</strong> than it is in English:class Lunch:def _ _init_ _(self):# Make/embed Customer and Employeeself.cust = Customer( )self.empl = Employee( )def order(self, foodName):# Start a Customer order simulationself.cust.placeOrder(foodName, self.empl)def result(self):# Ask the Customer about its Foodself.cust.printFood( )670 | 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!