Search code examples
pythonlistclassmethodsself

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


I am trying to call a list form init function to a method in the same 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') 

But I am getting this error.

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

I have used the self keyword. How to rectify this


Solution

  • Firstly, as indicated by the error you posted, there is no self for the e_list throwing the error. You need to use self.e_list everytime you want to reference that specific list inside your instance.

    Secondly, your variable i is not a number, but an employee, so you should name it accordingly. That will also reveal why e_list[i] will give you an index error.

        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')