1. What are the characteristics of object orientation
Three characteristics of object-oriented: encapsulation, inheritance and polymorphism
2. Encapsulation in Python
In Python code, encapsulation has two meanings:
- Encapsulation is the operation of writing the properties and methods of the real-world subject into the class
class Person(): # Encapsulation properties # Packaging method
- Encapsulation can be added as private permissions for properties and methods
2.1 private properties and private methods in encapsulation
In object-oriented code, we can divide attributes and methods into two categories
- Public (attribute, method)
- Private (property, method)
Public properties and public methods: we can operate on properties and methods both inside and outside the class.
However, in some cases, we do not want to operate on the properties and methods inside the class outside the class. We can encapsulate this property or method into a private form.
2.2 access restrictions on private attributes
The way to set private properties and methods is very simple: precede the property name and method name with two underscores__ Just.
Basic grammar
class Girl(): def __init__(self, name): self.name = name self.__age = 18 xiaomei = Girl('Xiaomei') print(xiaomei.name) print(xiaomei.__age) # An error is reported, indicating that the Girl object does not exist__ age attribute
Private properties and private methods in a class cannot be inherited by its subclasses.
From the above code, we can see that private properties cannot be accessed directly outside the class. However, for various reasons, we want to access private properties externally. What should we do?
A: we can define a statistical access "interface" (function) to access private properties.
2.3 private attribute setting and access interface
In Python, the function name 'get' is generally defined_ XX 'used to obtain private attributes, define' set_xx 'is used to modify private property values.
class Girl(): def __init__(self, name): self.name = name self.__age = 18 # Public method: the access interface provided to the outside def get_age(self): # Personal access: allow direct access # Outsiders' access: add restrictions return self.__age # Public method: the setting interface provided to the outside def set_age(self, age): self.__age = age girl = Girl('Xiaomei') girl.set_age(19) print(girl.get_age())
2.4 private method
The definition of private methods is basically the same as that of private attributes. Add two underscores in front of the method name__ Method name ()
2.5 what is the meaning of encapsulation
- Project development with object-oriented programming idea
- Encapsulating data attributes: clearly distinguish between inside and outside, and control the external operation behavior of hidden attributes (filter out abnormal data)
class People(): def __init__(self, name, age): self.__name = name self.__age = age def tell_info(self): print('Name:<%s> Age:<%s>' % (self.__name, self.__age)) # Access interface to private properties def set_info(self, name, age): if not isinstance(name, str): print('Name must be a string type') return if not isinstance(age, int): print('Age must be numeric') return self.__name = name self.__age = age p = People('jack', 38) p.tell_info() p.set_info('jennifer', 18) p.tell_info() p.set_info(123, 35) p.tell_info()
- The significance of private method encapsulation: reducing program complexity
class ATM: def __card(self): print('Card insertion') def __auth(self): print('User authentication') def __input(self): print('Enter withdrawal amount') def __print_bill(self): print('Print bill') def __take_money(self): print('withdraw money') # Define a public method for providing services externally def withdraw(self): self.__card() self.__auth() self.__input() self.__print_bill() self.__take_money() atm = ATM() atm.withdraw()
3. Inheritance in Python
3.1 what is inheritance
Let's talk about "inheritance" in Python code: a class is an abstract model used to describe the common characteristics of the same group of transactions in the real world, but a class also has hierarchy and scope, such as: biology = > animals = > mammals = > primates = > humans = > yellow people
Philosophically speaking, it is the relationship between commonness and individuality, such as white horse and horse! Therefore, we should also reflect the commonness and individuality relationship between classes in OOP code, which needs to be reflected through class inheritance. Simply put, if a Class A uses the members (properties and methods) of another class B, we can say that class a inherits class B. at the same time, this also reflects the characteristics of code reuse in OOP!
3.2 basic syntax of inheritance
It is assumed that class A inherits all properties and methods in class B (except private properties and methods)
class B(object): pass clss A(B): pass a = A() a.B All public properties in a.B All public methods in
case
Inheritance relationship between Person class and Teacher and Student classes
class Person(object): def eat(self): print('i can eat food!') def speak(self): print('i can speak!') class Teacher(Person): pass class Student(Person): pass teacher = Teacher() teacher.eat() teacher.speak() student = Student() student.eat() studnet.speak()
3.3 several concepts related to inheritance
- Inheritance: when a class obtains the relevant characteristics of its members from another existing class, it is called inheritance!
- Derivation: generating a new class from an existing class is called derivation!
Obviously, inheritance and derivation are actually the same concepts described from different directions. They are essentially the same!
- Parent class: also known as base class, it refers to an inherited class!
- Subclass: also called derived class or extended class
- Extension: adding some unique features to subclasses is called extension. Without extension, inheritance is meaningless!
- Single inheritance: a class can only inherit from one other class and cannot inherit multiple classes. Single inheritance is also a feature of most object-oriented languages!
- Multiple inheritance: a class inherits multiple parent classes at the same time (C + +, Python and other languages support multiple inheritance)
3.4 single inheritance
Single inheritance: a class can only inherit from one other class, and cannot inherit multiple classes. This class will have properties and methods with parent classes.
Basic grammar
# 1. Define a generic class (parent class) class Person(object): pass # 2. Define a personality class (subclass) class Teacher(Person): pass
case
For example, cars can be divided into two types (gasoline vehicles and electric vehicles)
# 1. Define a generic class (vehicle class) class Car(object): def run(self): print('i can run') # 2. Define gasoline vehicles class GasolineCar(Car): pass # 3. Defining electric vehicles class EletricCar(Car): pass bwm = GasolineCar() bwm.run()
3.5 single inheritance feature: transitivity
In Python inheritance, for example, class A inherits class B, and class B inherits class C. According to the transitivity of inheritance, class A will automatically inherit all public properties and methods in class C
class C(object): def func(self): print('I am C Related methods in class func') class B(C): pass class A(B): pass a = A() a.func()
3.6 common problems in writing object-oriented code
- Problem 1: when defining a class, it does not follow the naming rules of the class
A: in Python, classes are theoretically case insensitive. However, certain naming rules should be followed: the first letter must be a letter or underscore, which can contain letters, numbers and underscores, and the naming method is required to adopt the big hump. For example, electric vehicle: EletricCar
- Question 2: must a parent class inherit an object? Car(object)
A: in Python object-oriented code, it is recommended to let the parent class automatically inherit the object class when writing it. But it's OK not to write, because by default, all classes in Python inherit from object.
3.7 multi inheritance
What is multi inheritance? The so-called multi inheritance is a feature that allows a class to inherit from multiple classes at the same time. Python is one of the few programming languages that supports multiple inheritance.
Basic grammar
class B(object): pass class C(object): pass class A(B, C): pass a = A() a.B All properties and methods in a.C All properties and methods in
case
Gasoline vehicle, electric vehicle = > hybrid vehicle (vehicle + electric)
class GasolineCar(object): def run_with_gasoline(self): print('i can run with gasoline') class EletricCar(object): def run_with_eletric(self): print('i can run with eletric') class HybridCar(GasolineCar, EletricCar): pass tesla = HybridCar() tesla.run_with_gasoline() tesla.run_with_eletric()
Note: Although multiple inheritance allows us to inherit from multiple classes at the same time, we should try to avoid using multiple inheritance in actual development, because naming conflicts will occur if the same properties and methods appear in two classes
3.8 subclass extension: override parent class properties and methods
Extension feature: inheritance allows subclasses to inherit all public properties and methods of the parent class. However, if it is only to inherit public properties and methods, inheritance has no practical significance. It should be that after inheritance, subclasses should have some own properties and methods.
What is rewriting?
Override is also called override, which means that when the child class member has the same name as the parent class member, the members inherited from the parent class will be redefined!
At this time, when accessing related members through the object instantiated from the subclass, the real role is the members defined in the subclass!
In the above single inheritance example, the subclasses Cat and Dog of Animal inherit the properties and methods of the parent class, but our Dog dog has its own bark 'bark' and Cat has its own bark 'meow'. At this time, we need to reconstruct the call() method of the parent class. As follows:
class Animal(object): def eat(self): print('i can eat') def call(self): print('i can call') class Dog(Animal): pass class Cat(Animal): pass wangcai = Dog() wangcai.eat() wangcai.call() miaomiao = Cat() miaomiao.eat() miaomiao.call()
Dog and Cat subclasses override the call method in the parent class Animal:
class Animal(object): def eat(self): print('i can eat') # Public method def call(self): print('i can call') class Dog(Animal): # Override the call method of the parent class def call(self): print('i can wang wang wang') class Cat(Animal): # Override the call method of the parent class def call(self): print('i can miao miao miao') wangcai = Dog() wangcai.eat() wangcai.call() miaomiao = Cat() miaomiao.eat() miaomiao.call()
Think: after rewriting the call method in the parent class, is the call method still in the parent class?
A: it's still there, but it's overridden in its subclass. The calling sequence of class methods. After we reconstruct the method of the parent class in the subclass, the instance of Cat subclass will first find the method in its own Cat class. When the method cannot be found, it will find the corresponding method in the parent class Animal.
3.9 super() calls parent class properties and methods
super(): call the parent class property or method, complete writing: Super (current class name, self). Attribute or method (). In Python3 version, call the properties and methods of the parent class. We only need to use super(). Attribute or super(). The method name () can be called.
Case: Car car, GasolineCar gasoline Car, electric Car
class Car(object): def __init__(self, brand, model, color): self.brand = brand self.model = model self.color = color def run(self): print('i can run') class GasolineCar(Car): def __init__(self, brand, model, color): super().__init__(brand, model, color) def run(self): print('i can run with gasoline') class ElectricCar(Car): def __init__(self, brand, model, color): super().__init__(brand, model, color) # Battery properties self.battery = 70 def run(self): print(f'i can run with electric,remain:{self.battery}') bwm = GasolineCar('bmw', 'X5', 'white') bwm.run() tesla = ElectricCar('Tesla', 'Model S', 'gules') tesla.run()
3.10 MRO attribute or MRO method: method resolution order
MRO(Method Resolution Order): method resolution order. We can use the class name__ mro__ Or class name. mro() to obtain the "class hierarchy", and the method parsing order is also found according to the "class hierarchy".
class Car(object): def __init__(self, brand, model, color): self.brand = brand self.model = model self.color = color def run(self): print('i can run') class GasolineCar(Car): def __init__(self, brand, model, color): super().__init__(brand, model, color) def run(self): print('i can run with gasoline') class ElectricCar(Car): def __init__(self, brand, model, color): super().__init__(brand, model, color) # Battery properties self.battery = 70 def run(self): print(f'i can run with electric,remain:{self.battery}') print(ElectricCar.__mro__) print(ElectricCar.mro())
The object class is also the base class of all classes (the search is terminated because it is related to the object)
4. Polymorphism in Python
4.1 what is polymorphism
Polymorphism means that a kind of thing has many forms.
definition
Polymorphism is a way of using objects. Subclasses override parent methods and call the same parent methods of different subclass objects to produce different execution results.
- Polymorphic dependent inheritance
- Subclass methods must override parent methods
First, define a parent class that may have multiple subclass objects. When we call a public method, different objects are passed, and different results are returned.
benefit
Flexible call, with polymorphism, it is easier to write general code and make general programming to adapt to the changing needs!
4.2 schematic diagram
The public interface service is the embodiment of polymorphism. It can return different results with different incoming fruit objects.
code implementation
Polymorphism: it can be based on inheritance or not
class Fruit(object): # Public method def makejuice(self): print('i can make juice') class Apple(Fruit): def makejuice(self): print('i can make apple juice') class Banana(Fruit): def makejuice(self): print('i can make banana juice') class Orange(Fruit): def makejuice(self): print('i can make orange juice') class Peach(Fruit): def makejuice(self): print('i can make peach juice') # Define public methods such as service def service(obj): obj.makejuice() apple = Apple() banana = Banana() orange = Orange() for i in (apple, banana, orange): service(i)
5. Other object-oriented features
Class 5.1 attributes
In Python, attributes can be divided into instance attributes and class attributes.
Class attribute is the attribute defined in the class object, which is shared by all instance objects of the class. It is usually used to record the characteristics related to this type, and class attributes are not used to record the characteristics of specific objects.
In Python, everything is an object. Class is also a special object. We can define properties for class separately.
class Person(object): # Define class properties count = 0 def __init(self, name, age): self.name = name self.age = age p1 = Person('Tom', 23) p2 = Person('Harry', 26)
5.2 class attribute code implementation
Define the count class attribute, which is used to record the number of objects generated by instantiating the Person class.
class Person(object): # Define class attribute count count = 0 # Define a__ init__ Magic method for initialization def __init__(self, name): self.name = name # Perform a + 1 operation on the count class attribute to record the total number of objects generated by the Person class Person.count += 1 # 1. Instantiate object p1 p1 = Person('Tom') p2 = Person('Harry') p3 = Person('Jennifer') # 2. Output class properties outside the class print(f'We use it together Person Class generated{Person.count}Instance objects')
Class 5.3 method
Why class methods are needed? In object-oriented, special emphasis is placed on data encapsulation. Therefore, it is not recommended to set and obtain properties directly outside the class. Therefore, if we want to manipulate class properties, we recommend using class methods.
class Tool(object): # Define a class attribute count count = 0 # Define a__ init__ Initialization method def __init__(self, name): self.name = name Tool.count += 1 # Encapsulate a class method: specifically implement the operation on the attribute of Tool.count class @classmethod def get_count(cls): print(f'We use Tool Class co instantiated{cls.count}Tools') t1 = Tool('axe') t2 = Tool('Hammer') t3 = Tool('Shovel') Tool.get_count()
Class methods are mainly used to manipulate class properties or other methods in the class.
5.4 static method
During development, if you need to encapsulate a method in a class, this method:
- There is no need to access instance properties or call instance methods
- There is no need to access class properties or call class methods
At this time, you can encapsulate this method into a static method.
Sample code
# Develop a game class Game(object): # Start the game and print the game function menu @staticmethod def menu(): print('1,Start the game') print('2,Game pause') print('3,Exit the game') # Start game, print menu Game.menu()
6. Comprehensive case
requirement analysis
Design a Game class.
attribute
- Define a class attribute top_score records the highest score in the history of the game
- Define an instance property player_name records the player name of the current game
method
- Static method show_help displays game help information
- Class method show_top_score displays the highest score in history
- Instance method start_game starts the current player's game
Sample code
class Game(object): # 1. Define class attribute top_score top_score = 0 # 2. Define initialization method__ init__ def __init__(self, player_name): self.player_name = player_name # 3. Define static methods for outputting help information @staticmethod def show_help(): print('Game help information') # 4. Define class methods @classmethod def show_top_score(cls): print(f'The highest score in the history of this game:{cls.top_score}') # 5. Define instance method, start_game() def start_game(self): print(f'{self.player_name},The game begins. Are you ready?') # Instantiate a class to generate an instance object mario = Game('itheima') mario.start_game() # Displays the highest score in history Game.show_top_score() # Pop up game help information Game.show_help()