在 Python 中的相同 class 中从一种方法调用列表到另一种方法

Calling a list from one method to another in the same class in Python

我正在尝试将列表形式的初始化函数调用到同一 class 中的方法。

class department():
    def __init__(self,d_name,e_list):
        self.d_name=d_name
        self.e_list=e_list
    def calsal(self,bonus,designation):
        count=0
        for i in self.e_list:
            if e_list[i].employee_name.lower()==designation.lower():
                salary.update_salary(bonus)
                print(e_list[i].employee_id)
                print(e_list[i].employee_name)
                print(e_list[i].designation)
                print(e_list[i].salary)
                count=1
        if count==0:
            print('Employee Not Found') 

但是我收到了这个错误。

Traceback (most recent call last): File "C:/Users/aditya/Desktop/1.py", line 39, in dep.calsal(bonus,designation) File "C:/Users/aditya/Desktop/1.py", line 18, in calsal if e_list[i].employee_name.lower()==designation.lower(): NameError: name 'e_list' is not defined

我使用了 self 关键字。如何纠正这个问题

首先,如您发布的错误所示,e_list 没有自我抛出错误。每次要在实例中引用该特定列表时,都需要使用 self.e_list

其次,你的变量i不是一个数字,而是一个员工,所以你应该相应地命名它。这也将揭示为什么 e_list[i] 会给你一个索引错误。

    def calsal(self,bonus,designation):
        count=0
        for employee in self.e_list:
            if employee.employee_name.lower()==designation.lower():
                employee.salary.update_salary(bonus)
                print(employee.employee_id)
                print(employee.employee_name)
                print(employee.designation)
                print(employee.salary)
                count=1
        if count==0:
            print('Employee Not Found')