[英]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.我正在尝试将列表表单 init function 调用到同一 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回溯(最后一次调用):文件“C:/Users/aditya/Desktop/1.py”,第 39 行,在 dep.calsal(bonus,designation) 文件“C:/Users/aditya/Desktop/1.py ",第 18 行,如果 e_list[i].employee_name.lower()==designation.lower(): NameError: name 'e_list' is not defined
I have used the self keyword.我使用了 self 关键字。 How to rectify this如何纠正这个
Firstly, as indicated by the error you posted, there is no self for the e_list throwing the error.首先,如您发布的错误所示,e_list 没有 self 引发错误。 You need to use self.e_list
everytime you want to reference that specific list inside your instance.每次要在实例中引用该特定列表时,都需要使用self.e_list
。
Secondly, your variable i
is not a number, but an employee, so you should name it accordingly.其次,你的变量i
不是一个数字,而是一个员工,所以你应该相应地命名它。 That will also reveal why e_list[i]
will give you an index error.这也将揭示为什么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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.