python定义员工类,每个员工包含姓名和薪资属性,统计员工总人数与总薪资。 创建员工对象,输出员工的信息,输出员工总人数和总薪资,并计算2位员工的薪资的和
时间: 2024-03-17 14:43:22 浏览: 56
好的,我来给您写一个 Python 的员工类示例代码:
```python
class Employee:
total_employees = 0
total_salary = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.total_employees += 1
Employee.total_salary += salary
def __str__(self):
return f"Name: {self.name}, Salary: {self.salary}"
# 创建员工对象
emp1 = Employee("Tom", 5000)
emp2 = Employee("Jerry", 6000)
# 输出员工信息
print(emp1)
print(emp2)
# 输出员工总人数和总薪资
print("Total employees:", Employee.total_employees)
print("Total salary:", Employee.total_salary)
# 计算2位员工的薪资的和
sum_salary = emp1.salary + emp2.salary
print("Sum of 2 employees' salary:", sum_salary)
```
输出结果如下:
```
Name: Tom, Salary: 5000
Name: Jerry, Salary: 6000
Total employees: 2
Total salary: 11000
Sum of 2 employees' salary: 11000
```
以上就是一个简单的员工类示例,您可以根据自己的需要进行修改和扩展。
阅读全文