使用您的示例的扩展版本
class Salary:
def __init__(self,pay):
self.pay=pay
def get_total(self):
return (self.pay*12)
def increase(self):
self.pay *= 1.1
class Employee:
def __init__(self,pay,bonus):
self.pay=pay
self.bonus=bonus
self.obj_salary=Salary(self.pay)
def annual_salary(self):
return "Total: " + str(self.obj_salary.get_total()+self.bonus)
obj_emp=Employee(100,10)
print (obj_emp.annual_salary())
调用employee.salary.increase 比调用employee.increase 更有意义
另外,如果您需要多个对象怎么办?您会继承其中一个还是全部继承导致可能的名称冲突?
class Game:
def __init__(self):
self.screens = [LoadingScreen, MapScreen]
self.player = Player()
self.display = Display()
self.stats = Stats(self.display)
self.screenIndex = self.player.getScreen()
self.currentScreen = self.screens[self.screenIndex]()
self.run()
* 编辑 *
看完这个
but on looking it up again i find that increase could be renamed to increaseSalary so employee.increaseSalary() would make sense right?
您可以简单地将增加的内容移至员工类,但如果您有经理类或老板类,您需要为每个类重复相同的代码
class Employee:
def __init__(self,pay,bonus):
self.pay=pay
self.bonus=bonus
def annual_salary(self):
return "Total: " + str(self.obj_salary.get_total()+self.bonus)
def increase_salary(self):
self.pay *= 1.1
class Manager:
def __init__(self,pay,bonus):
self.pay=pay
self.bonus=bonus
def annual_salary(self):
return "Total: " + str(self.obj_salary.get_total()+self.bonus)
def increase_salary(self):
self.pay *= 1.1
class Boss:
def __init__(self,pay,bonus):
self.pay=pay
self.bonus=bonus
def annual_salary(self):
return "Total: " + str(self.obj_salary.get_total()+self.bonus)
def increase_salary(self):
self.pay *= 1.1
或者只有一次
class Salary:
def __init__(self,pay):
self.pay=pay
def get_total(self):
return (self.pay*12)
def increase(self, addition):
self.pay *= addition
您还可以使用类方法更容易地找到平均值、最大值、最小值等