我正在尝试更多地了解Python中的类和对象,以下是教程中给出的示例。在下面的代码我正在使用:
class Employee(object):
'common base clase for all employee'
empCount = 0
def __init__(self, name, surname, pay):
self.name = name
self.surname = surname
self.pay = pay
Employee.empCount += 1
def displayCount(self):
print('Total employee {}'.format(Employee.empCount))
def displayEmployee(self):
print('Name: ', self.name, ', Surname: ', self.surname, ', Pay: ', self.pay)
def summPay(self):
pass
我已经转到了第2类对象emp1
和emp2
emp1 = Employee('Federico', 'Olivieri', '5000')
emp2 = Employee('Anonymous', 'Friend', '6500')
我想要的是在summPay
课程下创建另一个方法Employee
来计算所有工资的总和。我知道我可以尝试使用局部变量并为empCount
增加变量,但我想知道是否有更优雅的方法来做到这一点。
答案 0 :(得分:0)
class Employee(object):
'common base clase for all employee'
empCount = 0
sum = 0
def __init__(self, name, surname, pay):
self.name = name
self.surname = surname
self.pay = pay
Employee.empCount += 1
Employee.sum+=pay
def displayCount(self):
print('Total employee {}'.format(Employee.empCount))
def displayEmployee(self):
print('Name: ', self.name, ', Surname: ', self.surname, ', Pay: ', self.pay)
def summPay(self):
return self.sum
emp1 = Employee('Federico', 'Olivieri', 5000)
emp2 = Employee('Anonymous', 'Friend', 6500)
print(emp2.summPay())
这里初始化一个变量sum,在创建每个对象之后,调用构造函数并在构造函数sum中递增。
在最后一个对象创建之后,调用函数summPay()