object-oriented programming
Classes and objects
-
Class: an abstract concept obtained after extracting the common features of objects with common features (static and dynamic features)
-
Object: an entity that receives messages. Object-oriented programming aims to solve problems by sending messages to objects
Object = data + function (method) - > object logically turns data and the function of operating data into a whole.
-
Scope of object:
Everything is an object
Objects have properties and behaviors
Each object is unique
The object must belong to a class
-
Relationship between class and object:
A class is the blueprint (template) of an object. Only with a class can an object of this type be created; an object is an instance of a class.
-
Instruction programming - > procedure (function) oriented programming - > there are no problems when the program is relatively simple
Programming paradigm (methodology of programming): object oriented programming / functional programming
-
Steps of object-oriented programming:
1. Definition class
Data abstraction: find static features (attributes) related to objects - > find nouns
Behavior abstraction: find dynamic features (Methods) related to objects - > find verbs
2. Manufacturing object
3. Send a message
""" example01 - object-oriented programming Author: Asus Date: 2021/8/5 """ class Student: """student""" # Data abstraction def __init__(self, name, age): self.name = name self.age = age # Behavior abstraction (method) def eat(self): """having dinner""" print(f'{self.name}I am eating.') def study(self, course_name): """study :param course_name: curriculum """ print(f'{self.name}I am learning{course_name}') def play(self, game_name): print(f'{self.name}Playing{game_name}') def watch_av(self): if self.age < 18: print(f'{self.name}Under the age of 18, you can only see bears') else: print(f'{self.name}I'm watching Island movies')
""" example02 - create object/Send message to object Author: Asus Date: 2021/8/5 """ from example01 import Student # Step 2: create object -- > constructor syntax -- > class name (...,...) stu1 = Student('Zhang San', 15) stu2 = Student('Li Si', 20) # Step 3: Send a message to the object (call the method of the object): object. Method # Student.study(stu1, 'Python programming') stu1.study('Python Programming') stu1.eat() stu1.watch_av() stu1.age = 19 # Modify age stu1.watch_av() stu2.play('fight against landlords') stu2.watch_av()
example
- If a swimming pool is built (the radius is unknown), it is known that the cost of the outer wall is 32.5 yuan per perimeter and the cost of the aisle is 58.5 yuan per area. What is the total cost? (realized by object-oriented programming)
""" example03 - Solving practical problems with object-oriented programming Circle: The most important attribute: radius( radius) The most important method: perimeter( perimeter),Area( area) Author: Asus Date: 2021/8/5 """ import math class Circle: def __init__(self, radius): self.radius = radius def perimeter(self): """Calculated perimeter""" return 2 * math.pi * self.radius def area(self): """Calculated area""" return math.pi * self.radius ** 2 if __name__ == '__main__': r = float(input('Please enter the radius of the swimming pool:')) c1, c2 = Circle(r), Circle(r + 3) fence_price = c2.perimeter() * 38.5 aisle_price = (c2.area() - c1.area()) * 58.5 print(f'Cost of enclosure:{fence_price:2f}element') print(f'Cost of aisle:{aisle_price:2f}element') print(f'Total cost:{fence_price + aisle_price}element')
- Make a countdown timer
""" homework01 - Countdown timer Author: Asus Date: 2021/8/5 """ import time class Clock: """Clock""" def __init__(self, hour, min, sec): self.hour = hour self.min = min self.sec = sec def run(self): """count down""" if self.hour == self.min == self.sec == 0: return -1 if self.sec != 0: self.sec -= 1 elif self.min != 0: self.sec = 60 self.min -= 1 elif self.hour != 0: self.min = 60 self.sec = 60 self.hour -= 1 self.sec -= 1 if self.sec == 0: self.min -= 1 if self.min == 0: self.hour -= 1 def show(self): """Display time""" return f'{self.hour:0>2d}:{self.min:0>2d}:{self.sec:0>2d}' if __name__ == '__main__': clock = Clock(0, 20, 10) while True: # os.system('cls') print(clock.show()) time.sleep(0.1) if clock.run() == -1: print('Time is up.') break
Four pillars of object-oriented programming:
- Abstraction: extract commonness (defining a class is an abstraction process, which requires data abstraction and behavior abstraction).
- encapsulation: logically assemble data and functions that manipulate data into a whole (object). Hide the implementation details and expose the simple calling interface
- inheritance: extend an existing class to create a new class
- polymorphism: send the same message to different objects, and different objects perform different behaviors
inherit
- Inheritance: extend an existing class to create a new class
Classes that provide inheritance information are called parent classes (superclasses and base classes), and classes that get inheritance information are called subclasses (derived classes)
Subclasses directly inherit public properties and behaviors from the parent class, and then add their own unique properties and behaviors,
Therefore, the subclass must be more powerful than the parent class. You can use the subclass object to replace the parent object at any time.
Inheritance is a means of reusing code, but it cannot be abused. Inheritance in Python allows multiple inheritance. A class can have one or more parent classes.
If you do not have to use multiple inheritance, try to use single inheritance.
""" example01 - inherit __slots__ = ('name', 'age') # __ slots__ Only these two attributes can be qualified Author: Asus Date: 2021/8/6 """ class Person: """people""" # __slots__ = ('name', 'age') # __ slots__ Only these two attributes can be qualified # Data abstraction def __init__(self, name, gender): self.name = name self.gender = gender # Behavior abstraction (method) def eat(self): """having dinner""" print(f'{self.name}I am eating.') def play(self, game_name): print(f'{self.name}Playing{game_name}') def introduce(self): if self.gender: sex = 'male' else: sex = 'female' print(f'My name is{self.name}, It's a{sex}people') class Student(Person): def __init__(self, name, gender, grade): # self.name = name # self.age = gender super().__init__(name, gender) self.grade = grade def study(self, course_name): """study :param course_name: curriculum """ print(f'{self.name}I am learning{course_name}') class Teacher(Person): """teacher""" def __init__(self, name, gender, title): super().__init__(name, gender) self.title = title def teach(self, course_name): """study :param course_name: curriculum """ print(f'{self.name}{self.title}Teaching{course_name}') class Programmer(Person): """programmer""" def write_code(self, programming_language): """Write code""" print(f'{self.name}Writing{programming_language}Write code') stu = Student('Daji', False, 'fifth grade') stu.study('mathematics') stu.play('Glory of Kings') stu.eat() stu.introduce() print('-' * 40) teacher = Teacher('Zhuge Liang', True, 'professor') teacher.eat() teacher.play('fight against landlords') teacher.teach('python Programming') teacher.introduce() print('-' * 40) pro = Programmer('Yuan Fang', True) pro.write_code('python')
polymorphic
-
Subclasses give their own implementation versions of the existing methods of the parent class. This process is called method override.
In the process of rewriting a method, different subclasses can give different implementation versions of the same method of the parent class, and the method will show polymorphic behavior at run time. -
Polymorphism: send the same message to different objects, and different objects perform different behaviors.
""" example03 - Salary (monthly salary) settlement system Three types of employees: Department Manager: fixed monthly salary, 15000 Programmer: Hourly settlement monthly salary, 200 yuan per hour Salesperson: base salary+Commission, base salary 1800 yuan, sales 5%Commission Enter employee information and automatically settle monthly salary Author: Asus Date: 2021/8/6 """ class Employee: def __init__(self, number, name): self.number = number self.name = name def get_salary(self): pass class Manager(Employee): def get_salary(self): return 15000 class Programmer(Employee): def __init__(self, number, name): super().__init__(number, name) self.working_hour = 0 def get_salary(self): return 200 * self.working_hour class Salesman(Employee): def __init__(self, number, name): super().__init__(number, name) self.sales = 0 def get_salary(self): return 1800 + self.sales * 0.05 def main(): emps = [ Manager(1122, 'Liu Bei'), Programmer(2233, 'Zhuge Liang'), Salesman(3344, 'Guan Yu'), Salesman(4455, 'Fei Zhang') ] for emp in emps: if type(emp) == Programmer: emp.working_hour = int(input(f'Please enter{emp.name}Duration of this month:')) elif type(emp) == Salesman: emp.sales = float(input(f'Please enter{emp.name}Sales this month:')) print(f'{emp.name}Salary of this month:{emp.get_salary()}element') if __name__ == '__main__': main()