Learning Python - Mark Lutz [597]
res = []
for x in self: # Scan first sequence
for other in others: # For all other args
if x not in other: break # Item in each one?
else: # No: break out of loop
res.append(x) # Yes: add item to end
return Set(res)
def union(*args): # self is args[0]
res = []
for seq in args: # For all args
for x in seq: # For all nodes
if not x in res:
res.append(x) # Add new items to result
return Set(res)
Your interaction with the extension will look something like the following. Note that you can intersect by using & or calling intersect, but you must call intersect for three or more operands; & is a binary (two-sided) operator. Also, note that we could have called MultiSet simply Set to make this change more transparent if we used setwrapper.Set to refer to the original within multiset:>>> from multiset import *
>>> x = MultiSet([1,2,3,4])
>>> y = MultiSet([3,4,5])
>>> z = MultiSet([0,1,2])
>>> x & y, x | y # Two operands
(Set:[3, 4], Set:[1, 2, 3, 4, 5])
>>> x.intersect(y, z) # Three operands
Set:[]
>>> x.union(y, z)
Set:[1, 2, 3, 4, 5, 0]
>>> x.intersect([1,2,3], [2,3,4], [1,2,3]) # Four operands
Set:[2, 3]
>>> x.union(range(10)) # Non-MultiSets work, too
Set:[1, 2, 3, 4, 0, 5, 6, 7, 8, 9]
Class tree links. Here is the way I changed the lister classes, and a rerun of the test to show its format. Do the same for the dir-based version, and also do this when formatting class objects in the tree climber variant:class ListInstance:
def __str__(self):
return ' self.__class__.__name__, # My class's name self.__supers(), # My class's own supers id(self), # My address self.__attrnames()) ) # name=value list def __attrnames(self): ...unchanged... def __supers(self): names = [] for super in self.__class__.__bases__: # One level up from class names.append(super.__name__) # name, not str(super) return ', '.join(names) C:\misc> python testmixin.py name data2=eggs name data3=42 > Composition. My solution is below (file lunch.py), with comments from the description mixed in with the code. This is one case where it’s probably easier to express a problem in Python than it is in English:class Lunch: def __init__(self): # Make/embed Customer, Employee self.cust = Customer() self.empl = Employee() def order(self, foodName): # Start Customer order simulation self.cust.placeOrder(foodName, self.empl) def result(self): # Ask the Customer about its Food self.cust.printFood() class Customer: def __init__(self): # Initialize my food to None self.food = None def placeOrder(self, foodName, employee): # Place order with Employee self.food = employee.takeOrder(foodName) def printFood(self): # Print the name of my food print(self.food.name) class Employee: def takeOrder(self, foodName): # Return Food, with desired name return Food(foodName) class Food: def __init__(self, name): # Store food name self.name = name if __name__ == '__main__': x = Lunch() # Self-test code x.order('burritos') # If run, not imported x.result() x.order('pizza') x.result() % python lunch.py burritos pizza Zoo animal hierarchy. Here is the way I coded the taxonomy in Python (file zoo.py); it’s artificial, but the general coding pattern applies to many real structures, from GUIs to employee databases. Notice that the self.speak reference in Animal triggers an independent inheritance search, which finds speak in a subclass. Test this interactively per the exercise description. Try extending this hierarchy with new classes, and making instances of various classes in the tree:class Animal: def reply(self): self.speak() # Back to subclass def speak(self): print('spam') # Custom message class Mammal(Animal): def speak(self): print('huh?') class Cat(Mammal): def speak(self): print('meow') class Dog(Mammal): def speak(self): print('bark') class Primate(Mammal): def speak(self): print('Hello world!') class Hacker(Primate): pass # Inherit from Primate