python basics - day21

# Let's talk about multiple inheritance, the principle of inheritance,
# When a node can be accessed in depth and breadth, it is preferred to search from breadth
# These words also indirectly indicate that there are two ways to access that node,
# And the priority is to search from the breadth, which means that what can be found later, it will not be found for the time being.
#
#
# For some difficult codes, the translation layer Chinese helps to understand,
#
#
# To summarize, because this can help you store knowledge in days,
# Integrate into a whole, because when you actually use it, you don't know which knowledge point you will use,
#


# len () 和 __len __ ()
# The len() function can only be used in a class that implements the __len__() method
# def len2(obj): # normalized design
# return obj .__ len __ ()

# normalized design, that is,
# Lists, sets, tuples, etc., can get the length through the len() method,
# Because these types of data, inside their classes, all implement the same interface, that is, the __len__() method,

l = [1,2,3]
print(len(l)) #The print result is: 3
print(l.__len__()) #The print result is: 3
print('__len__' in list.__dict__) #Print result: True, indicating that the __len__ method is implemented in the list class,


# create a specification
from abc import ABCMeta, abstractmethod #!!!The abstract class in python needs to be implemented with the help of this module,
class Payment(metaclass=ABCMeta): #Abstract class interface class specification and constraints metaclass specifies a metaclass, indicating that this class is an abstract class (or an interface class)
                                      #Whether it is an abstract class or an interface class after metaclass=ABCMeta, it means that this class cannot be instantiated
    s = 'haha'
    @abstractmethod #After being modified by abstractmethod, the subclass inherits this method, and the subclass needs to implement it. If the subclass also intends to be an abstract class, I haven't tried it yet.
                                        # Print the __dict__ of the subclass, there will be '__abstractmethods__': frozenset({'pay'}), the key means an abstract method, at this time the subclass is also an abstract class,
                                        #So if the subclass does not implement the inherited abstract method, it cannot be instantiated,
                                        # View the abstract class by type, it will print: <class 'abc.ABCMeta'>, that is, the abstract class,
                                        #Sometimes, instead of saying that the abstract class method is not implemented, it is better to say that the subclass has inherited, and if the subclass is not implemented, it cannot be instantiated.
                                        # And to implement the inherited method, the first call is the method implemented by the subclass itself,
    def pay(self):
        print(Payment.s)
        pass # abstract method

class Alipay(Payment):
    pass
    def pay(self,money):
        pass
        # print(Payment.pay(money))
        # print('Pay %s yuan using Alipay'%money)

class QQpay(Payment):
    def pay(self,money):
        print('Use qq to pay %s yuan'%money)

class Wechatpay(Payment):
    def pay(self,money):
        print('Used WeChat to pay %s yuan'%money)
    def recharge(self):pass

def pay(a,money):
    a.pay(money)

a = Alipay()
a.pay(100)
print(Alipay.__dict__)
print(type(Alipay)) #<class 'abc.ABCMeta'>, which is an abstract class,
print(type(Payment))    #<class 'abc.ABCMeta'>


# There are so many calling methods that look similar. I want to say that after the normalized design, different classes can use the same function to call
a = Alipay()
a.pay(100)
pay(a,100) # Normalized design: no matter which class of object it is, the same function is called to complete similar functions
q = QQpay()
q.pay(100)
pay(q,100)
w = Wechatpay ()
pay(w,100) # If the pay method name of the Wechatpay class is changed to fukuan, an error will be reported here, so no error will be reported in this situation at present.

# ps:
#About the subclass must implement the method inherited from the abstract class, this implementation means that you must def, but the content inside can be a pass statement,
#The essence of an abstract class is still a class, which refers to the similarity of a group of classes, including data attributes (such as all_type) and function attributes (such as read, write), while the interface only emphasizes the similarity of function attributes.


# abstract classes and interface classes
# java programming principles and design patterns
# Design pattern programming The landmark design method evolved from java
# The singleton pattern is a design pattern, that is, a class has only one instance
## Introduction to Algorithms Computational methods Time and space issues authoritative and general

#java cannot have multiple inheritance

# Programming principles
    # python
    # open closed principle
        # open is open to extension
        # Closure is closed to modification
    # Dependency Inversion Principle
    # Interface isolation principle
# The program code that has been written is not allowed to be modified


# Dependency Inversion Principle: !!!!!!!
# High-level modules should not depend on low-level modules, both should depend on their abstractions; abstractions should not depend on details; details should depend on abstractions. In other words, program for the interface, not for the implementation


# 1, in the process of inheriting abstract classes, we should try to avoid multiple inheritance,
# 2, and when inheriting interfaces, we encourage you to inherit more interfaces,
#The first sentence is easy to understand. Abstraction makes our structure complicated. In the words of the previous multi-inheritance, it is to dig a hole for yourself.
#And the second sentence, it may be because one inherits from multiple, and the purpose of inheritance is to achieve unified implementation, so it is recommended, it still needs to be thought deeply


# 1, In abstract classes, we can make basic implementations of some abstract methods
# 2, and in the interface class, any method is just a specification, and the specific function needs to be implemented by the subclass
# Regarding the implementation of abstract class methods, I think it is more of a suggestion, the compiler does not enforce that you cannot write,
# Because from the perspective of the compiler, as long as you have def, even if the function implementation is pass, the compiler seems to think that you have implemented it.
# Secondly, the subclass inherits the abstract class. If the subclass does not implement the method of the parent class, it cannot be instantiated. After it is implemented, it will call its own method first.
# So we analyze it from multiple aspects, and we didn't want to implement any methods in the abstract class when we first defined the abstract class.
# So it can be understood that some basic implementations can be made in the abstract class, but not in the interface,
# The provisions of the top two sentences, I personally understand, are more of a suggestion.


#!!!!! I feel that the list and summary of the interface below are very concise, there is no need to modify it by yourself, just use it directly,
# What is an interface
# There is no concept of interface in python
# Where does the concept of interface come from?
    # There is no multiple inheritance interface for java classes to implement multiple inheritance
# describe the zoo
# Those who can swim, those who can walk, those who can climb trees and those who can fly
# Tiger
# frog
# swan
# monkey
from abc import ABCMeta,abstractmethod
class FlyAnimal(metaclass=ABCMeta):
    @abstractmethod
    def fly(self):pass
    @abstractmethod
    def cal_flying_speed(self):pass
    @abstractmethod
    def cal_flying_height(self):pass
class WalkAnimal(metaclass=ABCMeta):
    @abstractmethod
    def walk(self):pass
class SwimAnimal(metaclass=ABCMeta):
    @abstractmethod
    def walk(self):pass
class Tiger(WalkAnimal,SwimAnimal):
    def walk(self):pass
    def swim(self):pass
class Monkey:
    def walk(self):pass
    def climb(self):pass
class Swan(FlyAnimal,WalkAnimal,SwimAnimal):
    def swim(self):pass
    def walk(self):pass
    def fly(self):pass
    def cal_flying_speed(self):pass
    def cal_flying_height(self):pass
class Parrot(FlyAnimal):
    def fly(self):pass
    def cal_flying_speed(self):pass
    def cal_flying_height(self): pass
# All flying animals have some characteristics of flying animals
# All walking animals have some walking animal traits

# The role of the interface class:
    # In java, it can meet the interface isolation principle and complete the constraints of multiple inheritance
    # In python, the principle of interface isolation is satisfied. Since python itself supports multiple inheritance, the concept of interface is not needed.

# abstract classes and interface classes
# in python
    #No difference, they are all used to constrain methods in subclasses
    #As long as the methods decorated by abstractmethod in abstract classes and interface classes need to be implemented by subclasses
    #It should be noted that when multiple classes have the same function and different functions, multiple interface classes should be used to carry out separate constraints

# in java
    # Abstract classes are distinct from interfaces
    # The essence of an abstract class is that a class must follow the rules of single inheritance, so if a subclass is constrained by an abstract class, it can only be controlled by a parent class
    # When multiple classes have the same function and different functions, java can only use the interface to solve the problem

# during the interview
    # Abstract class is a specification for defining classes in python
    # Interface, ps:!!!!!!!! I added that the interface is a mechanism provided by java to help us solve the problem. Multiple classes have the same function and different functions.
# When writing code in the company class
    # If you encounter an abstract class, remember to implement the corresponding methods one by one according to the specifications in the abstract class, ps: I will add it myself, simply put, the project is written with the specifications of others as a reference,


# The interface is to standardize the writing method, especially in the case of multi-person programming, it is very important,
# And if you are alone, it is not so important to use the interface to standardize the writing,


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324479897&siteId=291194637