Inherit, Customize, and Extend

In fact, classes can be even more flexible than our example implies. In general, classes can inherit, customize, or extend existing code in superclasses. For example, although we’re focused on customization here, we can also add unique methods to Manager that are not present in Person, if Managers require something completely different (Python namesake reference intended). The following snippet illustrates. Here, giveRaise redefines a superclass method to customize it, but someThingElse defines something new to extend:

class Person:
    def lastName(self): ...
    def giveRaise(self): ...
    def __str__(self): ...

class Manager(Person):                        # Inherit
    def giveRaise(self, ...): ...             # Customize
    def someThingElse(self, ...): ...         # Extend

tom = Manager()
tom.lastName()                                # Inherited verbatim
tom.giveRaise()                               # Customized version
tom.someThingElse()                           # Extension here
print(tom)                                    # Inherited overload method

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

Extra methods like this code’s someThingElse extend the existing software and are available on Manager objects only, not on Persons. For the purposes of this tutorial, however, we’ll limit our scope to customizing some of Person’s behavior by redefining it, not adding to it.