簡體   English   中英

如何在python中打印使用class存儲的員工工資總和

[英]how to print the sum of salary of employees stored using a class in python

我創建了一個 class 來存儲所有員工的詳細信息並顯示相同的信息。 但是我必須顯示所有員工的工資總和。 我做不到。 誰能幫我......???

class Employee :
    empid = 0
    name = None
    salary = 0.0
    def getInput(self) :
        print("Enter the empid :: ", end ="")
        self.empid = input()
        print("Enter the name :: ", end ="")
        self.name = input()
        print("Enter the salary :: ", end ="")
        self.salary = input()
    def display(self) :
        print("Employee id = " + str(self.empid))
        print("Employee name = " + self.name)
        print("Employee salary = " + str(self.salary))
    def main( args) :
        e = [None] * (3)
        i = 0
        while (i < 3) :
            e[i] = Employee()
            e[i].getInput()
            i += 1
        print("**** Data Entered as below ****")
        i = 0
        while (i < 3) :
            e[i].display()
            i += 1
     
if __name__=="__main__":
    Employee.main([])

使用此存儲后如何打印員工的工資總額。???

首先,您需要從 class 中獲取main() 。然后,您應該實際添加計算工資總和的代碼。 sumsalary()未在您的代碼中的任何位置聲明,您沒有收到錯誤的原因是因為i的值大於3 ,因此無法訪問該部分。

我更新了您的代碼,以便它在不創建 function 的情況下計算總和。

class Employee :
    empid = 0
    name = None
    salary = 0.0
    def getInput(self) :
        print("Enter the empid :: ", end ="")
        self.empid = input()
        print("Enter the name :: ", end ="")
        self.name = input()
        print("Enter the salary :: ", end ="")
        self.salary = input()
    def display(self) :
        print("Employee id = " + str(self.empid))
        print("Employee name = " + self.name)
        print("Employee salary = " + str(self.salary))
    

def main(args):
        e = [None] * (3)
        i = 0
        while (i < 3) :
            e[i] = Employee()
            e[i].getInput()
            i += 1
        print("**** Data Entered as below ****")
        i = 0
        while (i < 3) :
            e[i].display()
            i += 1
            
        i=0
        sum_salary = 0
        while(i<3):
            sum_salary += int(e[i].salary)
            i += 1
        print("sum salary: " + str(sum_salary) )
            
if __name__=="__main__":
    main([])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM