您可以将函数作为另一个类中方法的参数吗?

时间:2020-03-26 02:30:00

标签: python

def hourlylist():
    newlist = []
    for Employee in employeeobject():
            if Employee.classification == "1":
                newlist.append(Employee.hourly)
    return newlist




class Hourly(Classification): #classification is parent class
    def __init__(self,rate,hourly): #list of hours worked
        self.hourly = hourly
        self.rate = rate
    def set_pay(hourlylist()): #hoursworked as parameter
        print(hourlylist())

所以我的列表来自功能小时列表的顶部。我想做的是将函数作为set_pay方法的参数。这可能吗?我可以在set_pay方法中将该函数作为参数调用并在方法内部调用它吗?

谢谢

1 个答案:

答案 0 :(得分:0)

def hourlylist():
    newlist = []
    for Employee in employeeobject():
            if Employee.classification == "1":
                newlist.append(Employee.hourly)
    return newlist




class Hourly(Classification): #classification is parent class
    def __init__(self,rate,hourly): #list of hours worked
        self.hourly = hourly
        self.rate = rate
    def set_pay(hourlylist): #hoursworked as parameter
        print(hourlylist)

但是如果要执行为什么将其作为参数的原因,这将为小时列表打印代码

def hourlylist():
    newlist = []
    for Employee in employeeobject():
            if Employee.classification == "1":
                newlist.append(Employee.hourly)
    return newlist




class Hourly(Classification): #classification is parent class
    def __init__(self,rate,hourly): #list of hours worked
        self.hourly = hourly
        self.rate = rate
    def set_pay(self): #hoursworked as parameter
        newlist = hourlylist() # to get newlist from function

确保在此类之前定义了小时列表