Python-class design details
Class Design
This article discusses the design of OOP in Python, that is, how to use classes to model useful objects. Compile the commonly used OOP Design Patterns in Python, such as inheritance, combination, delegation, and factory. In addition, we introduce some concepts of class design, such as pseudo-Private attributes and multi-inheritance.
========================================================== ==========================================================
Python and OOP
Python's OOP implementation is similar to Java and can be summarized into three concepts:
1. [inheritance] inheritance is based on the attribute search in Python (in the X. name expression)
2. [polymorphism] in the X. method, the meaning of method depends on the type of X.
3. [encapsulation] implements the behavior of methods and operators. Data Hiding is a convention by default.
========================================================== ==========================================================
OOP and inheritance: "A" Relationship
For example, the pizza shop team can define it through four classes in the file employees. py. The most common class of Employee provides common behaviors, such as salary increase (giveRaise) and printing (_ repr __). There are two types of employees, so the Employee has two sub-classes: Chef and Server (Chef and waiter ). Both subclasses will overwrite the inherited work method to print more specific information. Finally, the pizza robot is simulated by a more specific class: PizzaRobot is a Chef and an Employee. In OOP terms, these links are "is-a" Links: robots are chefs while chefs are employees. The code is written as follows:
#File employees.pyclass 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()
The running result is as follows:
bob makes pizza
Employee does stuffChef makes foodServer interfaces with customerPizzaRobot makes pizza
We can see that bob is a PizzaRobot, but it is still displayed as "Employee" during printing. The result shows no specific type of Employee, in this case, the _ repr _ method in the Employee class can be modified as follows:
def __repr__(self): return '