【问题标题】:Can I add to an Inherited Function?我可以添加到继承的函数吗?
【发布时间】:2014-11-25 01:13:06
【问题描述】:

我有以下代码:

    import locale
locale.setlocale(locale.LC_ALL, '') #Sets the locale to 'English_Canada.1252'
class Employee():
    #Initlizes all of the info I need from the user
    def __init__(self, lastName, firstName, payRate):
        self.nameL = lastName
        self.nameF = firstName
        self.payRate = payRate #This payRate is an hourly pay rate
    #Prints out the first and last name of the Employee in the form Employee(FirstName LastName)
    def __repr__(self):
        return('Employee(' + self.nameF + ' ' + self.nameL + ')')
    #Changes the '+' key to add the hourlyPayRate of 2 Employee class types together   
    def __add__(self, otherSelf):
        sumOfPay = self.payRate + otherSelf.payRate
        return(sumOfPay)
    def printCheque(self, numberOfHoursWorked):
        if (numberOfHoursWorked > 40):
           grossIncome = (numberOfHoursWorked - 40) * (self.payRate * 2)
           grossIncome = grossIncome + (40 * self.payRate)           
        else:
            grossIncome = numberOfHoursWorked * self.payRate
        if(grossIncome > 42000):
            taxPaid = grossIncome * 0.22
        else:
            taxPaid = grossIncome * 0.15
        moneyMade = grossIncome - taxPaid           
        print('-'*80 + '\n')
        print('PAY TO: '+ self.nameF + ' ' + self.nameL + ' '*38 + 'AMOUNT: ' + locale.currency(moneyMade)+'\n')
        print('\n')
        print('Gross Pay: '+locale.currency(grossIncome) + '\n')
        print('Deductions: \n')
        print('   Tax     ',locale.currency(taxPaid), '\n')       
        return('-'*78)  
class SalariedEmployee(Employee):
    ''
    #payRate inherited from Employee will refer to salary here.

我必须创建另一个类似于 Employee 的 Class,但是这个人的薪水超过了按小时支付的工资。我需要做的第一件事是将 payRate 更改为薪水。我不确定这会是什么样子,我尝试了一些方法,但没有奏效。

我需要做的另一件事是更改 printCheque 以包含其他税款,并显示假期时间。我是否可以在不定义新函数的情况下将类似的内容添加到函数中,还是必须创建一个全新的函数?

不太确定如何执行其中任何一项,您可以提供的任何帮助都会有很大帮助。

谢谢!

【问题讨论】:

    标签: python class inheritance overriding


    【解决方案1】:

    我可以建议再重构一点吗... 似乎小时工和受薪员工是应扩展基本 Employee 类的两种不同类型的员工。

    class Employee():
        #Initlizes all of the info I need from the user
        def __init__(self, lastName, firstName):
            self.nameL = lastName
            self.nameF = firstName
    
        def __repr__(self):
            return('Employee(' + self.nameF + ' ' + self.nameL + ')')
    
        def printCheque(self, grossIncome):
            if(grossIncome > 42000):
                taxPaid = grossIncome * 0.22
            else:
                taxPaid = grossIncome * 0.15
            moneyMade = grossIncome - taxPaid           
            print('-'*80 + '\n')
            print('PAY TO: '+ self.nameF + ' ' + self.nameL + ' '*38 + 'AMOUNT: ' + locale.currency(moneyMade)+'\n')
            print('\n')
            print('Gross Pay: '+locale.currency(grossIncome) + '\n')
            print('Deductions: \n')
            print('   Tax     ',locale.currency(taxPaid), '\n')       
            return('-'*78)
    
    
    class HourlyEmployee(Employee):
        def __init__(self, lastName, firstName, payRate):
            super(HourlyEmployee, self).__init__(lastName, firstName)
            self.payRate = payRate
    
        def __add__(self, otherSelf):
            sumOfPay = self.payRate + otherSelf.payRate
            return(sumOfPay)
    
        def printCheque(self, numberOfHoursWorked):
            if (numberOfHoursWorked > 40):
               grossIncome = (numberOfHoursWorked - 40) * (self.payRate * 2)
               grossIncome = grossIncome + (40 * self.payRate)           
            else:
                grossIncome = numberOfHoursWorked * self.payRate
    
            return super(HourlyEmployee, self).printCheque(grossIncome)
    
    
    class SalaryEmployee(Employee):
        def __init__(self, lastName, firstName, salary):
            super(HourlyEmployee, self).__init__(lastName, firstName)
            self.salary = salary
    
        def __add__(self, otherSelf):
            sumOfPay = self.salary + otherSelf.salary
            return(sumOfPay)
    
        def printCheque(self):
            cheque = super(SalaryEmployee, self).printCheque(self.salary)
            # Do Additional Tax Stuff and Add Vacation Hours
    

    执行上述操作应该有助于解决“我必须创建另一个类似于 Employee 的类,但是这个人的薪水超过了按小时支付的薪水。我需要做的第一件事是将 payRate 更改为薪水。我是不知道这会是什么样子,我尝试了一些方法,但没有奏效。”

    使用此类继承将使您能够根据员工类型更改属性。

    另外,我尝试稍微重构一下 printCheque 函数,以展示使用 super 函数如何帮助抽象出一些常见功能,然后在类级别的基础上添加功能。我不太确定所有打印功能发生了什么。最好使用字符串格式并将其返回,以便根据不同的类实例对其进行操作。

    【讨论】:

    • 如果不继承第三类怎么办。是否可以仅从 Employee 继承?还是我必须创建第三类。
    【解决方案2】:

    你可以在一堂课上做所有的事情。只需在方法中初始化对象而不是 _init__。

    class Employee():
    
        def __init__(self, firstName, lastName):
            self.firstName = firstName
            self.lastName = lastName
    
        def __repr__(self):
            pass
    
        def __addHourly__(self, payRate, extraPay):
            pass
    
        def __addSalary__(self, salary, extraPay):
            pass
    
        def printHourlyCheque(self, payRate, hoursWorked):
            pass
    
        def printSalaryCheque(self, Salary, vacationDays, sickDays):
            pass
    

    然后当你调用类时,只需使用 if 语句来选择调用哪些方法。

    employee = Employee.repr()
    status = some user input way to identify salary or hourly employee. 
        if status == 'Hourly':
            Employee.addHourly(payRate, extraPay)
            Employee.printHourlyCheque(payRate, #number of hours worked)
        elif status == 'Salary':
            Employee.adSalary
            Employee.printSalaryCheck(salary, #vacation days, #sick days)
    

    代码有点粗糙,但主要思想是在一个类中定义所有方法,然后在 main 中使用条件来调用与小时相关的方法或与薪水相关的方法。为此,请在方法本身中初始化对象,而不是在 init 中初始化对象,但名称等通用对象除外。

    【讨论】:

      猜你喜欢
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2014-02-25
      • 2013-03-11
      • 2011-01-21
      相关资源
      最近更新 更多