使用 for 循环创建类的实例

时间:2021-02-12 06:29:21

标签: python

我创建了一个类,它为每个对象获取名称、ID 号和薪水。类里面有加减工资和显示每个员工状态的函数:

class emp():
def __init__(self,name,id_num,salary):
    self.name=name
    self.id=id_num
    self.s=salary
    

    
def bounus(self,bon):
    self.s+=bon
    print(" the empolyee %s got a raise of %s"%(self.name,bon))
def ded(self,d):
    self.s-=d
    print(" the empolyee %s got a deduction of %s"%(self.name,d))
def show(self):
    s="the employee {} with id number {} has a salary of {}".format(self.name,self.id,self.s)
    print(s)

所以我想在“for”循环中使用“range”函数创建一些我的选择对象,如下所示:

for i in range(1,3) :
  o=str(input("Enter the employees number %s name\n"%i))
  p=input("Enter his\her id number\n")
  q=input("Enter his\her salary\n")
  ai=emp(o,p,q)
  ai.show()

以这种方式,它遍历 1 和 2 创建对象 a1 和 a2 并且它起作用了,但是当我尝试将它们显示在循环外时,如下所示:

a1.show()

它说,a1 是未定义的,尽管我可以在循环中显示它们,但我如何存储对象以便在循环后可以在它们上显示或应用函数。谢谢

4 个答案:

答案 0 :(得分:0)

Selcuk 确定了您的问题,但这里有一个基于您的代码的代码片段,可以帮助您概念化他的建议:

new_employees = []
for i in range(1,3):
    name = input("Enter the employees number %s name\n" %i)
    id_num = input("Enter his\her id number\n")
    salary = input("Enter his\her salary\n")
    employee = emp(name, id_num, salary)
    employee.show()
    new_employees.append(employee)

在循环结束时,您现在将拥有一个新员工列表,您可以使用这些员工做其他事情。因此,根据您的评论,假设您想从员工 ID 为 5 的员工的工资中扣除 25 美元。如果您不想花哨的话,可以这样做:

target_employee = None

for employee in new_employees:
   if employee.id == 5:
      target_employee = employee
      break

if target_employee:
   target_employee.ded(25)

答案 1 :(得分:0)

i 中的 ai 不会作为一个单独的变量进行处理,它只是成为一个完整的 ai

相反,您应该创建一个 list a,您可以使用 a[i] 访问它。

a = []
for i in range(2) : # Slight change to start at i=0
  o=str(input("Enter the employees number %s name\n"%i))
  p=input("Enter his\her id number\n")
  q=input("Enter his\her salary\n")
  a.append(emp(o,p,q))
  a[i].show()

答案 2 :(得分:0)

这是另一种按照您预期的方式为每个员工自动创建姓名并将该姓名和员工对象存储在字典中的方法。然后可以从循环外部按他的名字调用每个员工,并可以完全访问所有类方法。此外,类名应始终大写。对象名称为小写:

class Emp():
    def __init__(self, name, id_num, salary):
        self.name = name
        self.id = id_num
        self.s = salary

    def bonus(self, bon):
        self.s += bon
        print("The empolyee %s got a raise of %s" % (self.name, bon))

    def ded(self, d):
        self.s -= d
        print("The empolyee %s got a deduction of %s" % (self.name, d))

    def show(self):
        s = "The employee {} with id number {} has a salary of {}".format(self.name, self.id, self.s)
        print(s)

employees = {}
for i in range(1, 3):
    o = input("Enter the employees number %s name\n" % i)
    p = input("Enter his\her id number\n")
    q = int(input("Enter his\her salary\n"))

    emp = Emp(o, p, q)
    name = "a" + str(i)
    employees[name] = emp

employees["a1"].show()
employees["a2"].bonus(500)
employees["a2"].ded(200)
employees["a2"].show()

答案 3 :(得分:-1)

您犯的第一个错误是在 for 循环中声明了类。对象的范围仅限于 for 循环,将在循环后销毁,而且您不能将所有值写入循环,因为每次运行循环时都会调用新对象,从而销毁所有先前的对象,因此我们附加它们的列表并尝试

相关问题