Python——类的设计详解
Python——类的设计详解
类的设计这里讨论Python的OOP的设计问题,也就是如何使用类来对有用的对象进行建模。将编写Python中常用的OOP设计模式,例如,继承、组合、委托和工厂。另外介绍一些类设计的概念,例如伪私有属性、多继承等。
================================================================================
Python和OOP
Python的OOP实现与Java类似,可以概括为三个概念:
1.【继承】继承是基于Python中的属性查找(在X.name表达式中)
2.【多态】在X.method方法中,method的意义取决于X的类型
3.【封装】方法和运算符实现行为,数据隐藏默认是一种惯例
================================================================================
OOP和继承:“是一个”关系
举例说明:披萨店团队可以通过文件employees.py中的四个类来定义。最通用的类Employee提供共同行为,例如,加薪(giveRaise)和打印(__repr__)。员工有两种,所以Employee有两个子类:Chef和Server(厨师和服务员)。这两个子类都会覆盖继承的work方法来打印更具体的信息。最后,披萨机器人是由更具体的类来模拟:PizzaRobot是一种Chef,也是一种Employee。以OOP术语来看,这些关系为“是一个”(is-a)链接:机器人是一个主厨,而主厨是一个员工。代码编写如下:
#File employees.py class Employee: def __init__(self,name,salary = 0): self.name = name self.salary = salary def giveRaise(self,percent): self.salary = self.salary + (self.salary * percent) def work(self): print(self.name,'does stuff') def __repr__(self): return ''%(self.name,self.salary) class Chef(Employee): def __init__(self,name): Employee.__init__(self,name,50000) def work(self): print(self.name,"makes food") class Server(Employee): def __init__(self,name): Employee.__init__(self,name,40000) def work(self): print(self.name,'interfaces with customer') class PizzaRobot(Chef): def __init__(self,name): Chef.__init__(self,name) def work(self): print(self.name,'makes pizza') if __name__ == '__main__': bob = PizzaRobot('bob') print(bob) bob.work() bob.giveRaise(.2) print(bob) print() for klass in Employee,Chef,Server,PizzaRobot: obj = klass(klass.__name__) obj.work()
bob makes pizza Employee does stuff Chef makes food Server interfaces with customer PizzaRobot makes pizza
def __repr__(self): return '
热门文章:
相关内容
- 暂无相关文章
评论关闭