python---class(二):派生类覆盖基类中的方法

一、子类覆盖基类的方法,即:子类的方法名称与基类的方法重名,此时若想调用基类的该方法,需要:基类名.方法

代码注解:

python---class(二):派生类覆盖基类中的方法

代码:

#!/usr/bin/env python
#-*-coding:utf-8 -*-
class Employee:
    '''Class to represent an employee'''
    def __init__(self,first,last):
        '''Employee constructor takes first and last name'''
        self.firstName = first
        self.lastName = last
    def __str__(self):
        '''String representation of an Employee'''
        return "%s%s"%(self.firstName,self.lastName)
class HourlyWorker(Employee):
    '''Class to represent an employee paid by hour'''
    def __init__(self,first,last,initHours,initWage):
        '''Constructor for HourlyWorker,takes first and last name,
        inittial number of hours and initial Wage'''
        Employee.__init__(self,first,last)
        self.hours=float(initHours)
        self.wage=float(initWage)
    def getPay(self):
        '''Calculates HourlyWorker's weekly pay'''
        return self.hours * self.wage
    def __str__(self):
        '''String representation of HourlyWorker'''
        print("HourlyWorker.__str__ is executing")
        return "%s is an hourly worker with pay of $%.2f"% \
               (Employee.__str__(self),self.getPay())
#main program
hourly = HourlyWorker("Bob","Smith",40.0,10.0)
#invoke __str__method several ways
print("Calling __str__several ways...")
print(hourly)
print(hourly.__str__())
print(HourlyWorker.__str__(hourly))

代码结果:

Calling __str__several ways...
HourlyWorker.__str__ is executing
BobSmith is an hourly worker with pay of $400.00
HourlyWorker.__str__ is executing
BobSmith is an hourly worker with pay of $400.00
HourlyWorker.__str__ is executing
BobSmith is an hourly worker with pay of $400.00