[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
>>> for obj in db:
obj.giveRaise(.10) # default or custom

>>> for obj in db:
print(obj.lastName(), '=>', obj.pay)

Smith => 11000.0
Jones => 22000.0
Doe => 36000.0

Refactoring Code


Before we move on, there are a few coding alternatives worth noting here. Most of these
underscore the Python OOP model, and they serve as a quick review.


Augmenting methods


As a first alternative, notice that we have introduced some redundancy in Exam-
ple 1-16: the raise calculation is now repeated in two places (in the two classes). We
could also have implemented the customized Manager class by augmenting the inherited
raise method instead of replacing it completely:


class Manager(Person):
def giveRaise(self, percent, bonus=0.1):
Person.giveRaise(self, percent + bonus)

The trick here is to call back the superclass’s version of the method directly, passing in
the self argument explicitly. We still redefine the method, but we simply run the gen-
eral version after adding 10 percent (by default) to the passed-in percentage. This coding
pattern can help reduce code redundancy (the original raise method’s logic appears in
only one place and so is easier to change) and is especially handy for kicking off su-
perclass constructor methods in practice.


If you’ve already studied Python OOP, you know that this coding scheme works be-
cause we can always call methods through either an instance or the class name. In
general, the following are equivalent, and both forms may be used explicitly:


instance.method(arg1, arg2)
class.method(instance, arg1, arg2)

In fact, the first form is mapped to the second—when calling through the instance,
Python determines the class by searching the inheritance tree for the method name and
passes in the instance automatically. Either way, within giveRaise, self refers to the
instance that is the subject of the call.


Display format


For more object-oriented fun, we could also add a few operator overloading methods
to our people classes. For example, a str method, shown here, could return a string


Step 3: Stepping Up to OOP | 31
Free download pdf