简体   繁体   中英

Creating instances of a class using for loop

I have created a class that takes name,id number and salary for each object. inside the class there are functions for adding or deduction of the salary and showing the status for each employee:

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)

so I wanted to create a number of objects of my chioce using "range" function in the "for" loop as the following:

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

in that way, it loops through 1 and 2 creating objects a1 and a2 and it worked but when I try to show them outside the loop as the following:

a1.show()

it says,a1 is undefined although I could show them inside the loop, how can I store the objects so I can show or apply functions on them after looping.thanks

Selcuk identified your issue, but here is a code snippet based on your code that may help you conceptualize his advice:

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)

At the end of the loop you will now have a list of new employees that you can do other things with. So, per your comment assume you want to deduct $25 from the salary of on the employee with the employee id of 5. You could something like this if you didn't want to get fancy:

target_employee = None

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

if target_employee:
   target_employee.ded(25)

The i in ai does not get processed as a seperated variable, it just becomes one whole ai .

Instead, you should make a list a , which you can access with 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()

Here is another way that auto-creates a name for each employee the way you intended and stores that name and the employee object in a dictionary. Each employee can then be called by his name from outside the loop with full access to all the class methods. Also class names should always be capitalized. Object names are in lower case:

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

The first mistake you have done is declaring the class inside the for loop. The scope of the object is limited to the for loop and will be destroyed after the loop and moreover you cannot store all the values wrt to the loop as every time a loop is run the new object will be invoked destroying all the previous one hence us the list to append them and try

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM