Python object-oriented programming-02

Source: Internet
Author: User

This knowledge point refers to Liaoche's Python course [https://www.liaoxuefeng.com] Thanks to the free course of Turing's knowledge in Beijing [http://www.tulingxueyuan.com/]

2018/6/26 Tuesday 11:15:57

Inheritance and polymorphism
  • Inheritance is a class that can get member properties and member methods in another class
    • Function: Reduce code, increase code reuse function, and can set the class and class directly relationship
  • Inheritance vs. inherited concepts:
    • The inherited class is called the parent class, also called the base class, also called the superclass
    • Classes for inheritance, called subclasses, also called derived classes
    • There must be a is-a relationship between inheritance and inheritance
  • Inherited syntax:

        class Animal(object):        def run(self):        print("Animal is runnung...")    # Animal 继承于object,第一个类都继承于object,不管你写不写`object`    class Dog(Animal):        pass    # Dog继承于Animal    class Cat(Animal):        pass    # Cat继承于Animal
  • For Dog speaking, Animal it's the parent class, and for Animal that, Dog it's a subclass.
  • The benefit of inheritance is that subclasses get the full functionality of the parent class. DogThere's a Animal Run() way.

    >>> dog = Dog()# 子类一旦继承父类,则可以使用父类中除私有成员外的所有内容>>> dog.runAnimal is runnung...
  • We've made improvements to the code above Dog and Cat added some methods

        class Dog(Animal):        def run(self):            print(‘Dog is running...‘)    class Cat(Animal):        def run(self):            print(‘Cat is running...‘)
  • Run:

        >>> dog = Dog()    >>> cat = Cat()    >>> dog.run()    >>> cat.run()    Dog is running...    Cat is running...
  • As we can see here, the subclass and the parent class all have run methods, and the subclass run() overrides the parent class run() . The subclass is always called when the code is running run() . So we get another benefit of inheritance, polymorphism.

    Polymorphic
  • To understand what polymorphism is, let's start with a little more explanation of the data type. When we define a class, we actually define a data type. The data types we define are the same data types that python comes with, such as STR, list, dict:

        a = list() # a是list类型    b = Animal() # b是Animal类型    c = Dog() # c是Dog类型
  • Determining whether a variable is a type can be judged by isinstance ():

         >>> isinstance(a, list)     True     >>> isinstance(b, Animal)     True     >>> isinstance(c, Dog)     True
  • It seems that a b c There are three types of list, Animal, and dog.
  • But:

        >>> isinstance(c,Animal)    True
  • It seems C Dog is not just, C or Animal !
    But think about it, it makes sense, because it Dog is inherited from Animal , when we create an Dog instance of C, we think that the C data type is Dog correct, but C is Animal also true, Dog is a animal!
  • So, in an inheritance relationship, if the data type of an instance is a subclass, its data type can also be considered a parent class. However, the reverse is not possible:

        >>> b = Animal()    >>> isinstance(b, Dog)    False
  • To understand the benefits of polymorphism, we write a function

        def run_twice(animal):        animal.run()        animal.run()
  • When we pass in an instance of animal, Run_twice () prints out:

        >>> def run_twice(Animal()):    Animal is running..    Animal is running..
  • When we pass in the instance of Dog, Run_twice () prints out:

        >>> def run_twice(Dog()):    Dog is running..    Dog is running..
  • When we pass in an instance of cat, Run_twice () prints out:

        >>> def run_twice(Cat()):    Cat is running..    Cat is running..
  • If we define a tortoise type again, it is also derived from animal:

        class Tortoise(Animal):        def run(self):            print(‘Tortoise is running slowly...‘)  
  • When we call Run_twice (), an instance of the tortoise is passed in:

        >>> run_twice(Tortoise())    Tortoise is running slowly...    Tortoise is running slowly...
  • For a variable, we only need to know that it is a animal type, without knowing exactly its subtype, you can safely call the run () method, and the specific call of the run () method is on the animal, Dog, cat or Tortoise object, Determined by the exact type of the object at run time, this is the real power of polymorphism: The caller just calls, regardless of the details, and when we add a animal subclass, simply make sure that the run () method is written correctly, regardless of how the original code is called. This is the famous "opening and shutting" principle:

    • Open to extensions: Allow new animal subclasses;
    • Closed for modification: You do not need to modify functions such as run_twice () that depend on the animal type.

Add to:

    • Super ()
    • Subclasses if you want to extend the method of the parent class, you can access the parent class member for code reuse while defining the new method, you can call the parent class member using the format of the [parent class name. Parent class member], or you can use Super (). The format of the parent class member to invoke.

          class Animal(object):        def run(self):        print("Animal is runnung...")    class Dog(Animal):        def run(self):            print(‘Dog is running...‘)    class Cat(Animal):        def run(self):            super().run()            print(‘Cat is running...‘)
    • The problem of finding order of inherited variable functions
      • Prioritize finding your own variables
      • No, find the parent class
      • constructor If there is no definition in this class, automatic lookup calls the parent class constructor
      • If this class has a definition, it does not continue to look up
    • constructor function
      • is a special kind of function that is called before the class is instantiated
      • If a constructor is defined, the constructor is used when instantiating, and the parent class constructor is not found
      • If not defined, automatically finds the parent class constructor
      • If the subclass is not defined, the constructor of the parent class takes arguments, and the argument to construct the object should be constructed according to the parent class argument
Multiple inheritance in re-inheritance
  • An important way of inheriting object-oriented programming, by inheriting that subclasses can extend the functionality of the parent class
  • If we classify the animals we can think of
    • Dog-Dogs;
    • Bat-bat;
    • Parrot-Parrot;
    • Ostrich-Ostrich
  • We can fly, can run, can swim, mammals and other categories, it is too troublesome, the number of classes will be exponentially increased
  • Our correct approach is to use multiple inheritance, first of all, to install mammals at the primary level, and birds:

    class Animal(object):    pass# 大类:class Mammal(Animal):    passclass Bird(Animal):    pass# 各种动物:class Dog(Mammal):    passclass Bat(Mammal):    passclass Parrot(Bird):    passclass Ostrich(Bird):    pass
  • Then, we are adding runnable and flyable functions to animals, and we just need to define the classes of runnable and flyable first:

    class Runnable(object):    def run(self):        print(‘Running...‘)class Flyable(object):    def fly(self):        print(‘Flying...‘)

    -For animals that require runnable functionality, they inherit a runnable, such as dog:

    class Dog(Mammal, Runnable):    pass
  • For animals that require flyable functionality, they inherit more than one flyable, such as Bat:

    class Bat(Mammal, Flyable):    pass

    With multiple inheritance, a subclass can get all the functionality of multiple parent classes at the same time.

    • Mixin
    • Mixin design mode
      • The function of class is extended mainly by multi-inheritance method
      • Mixin concept
      • MRO and Mixin
      • Mixin mode
      • Mixin MRO
      • Mro
    • We use multiple inheritance syntax to implement Minxin
    • Use Mixin to implement multiple inheritance with great care
      • First he must show a single function, not an item
      • Responsibilities must be single, if multiple functions are written, then multiple mixin
      • Mixin cannot depend on the implementation of subclasses
      • Subclasses do not inherit this mixin class in time, they can still work, just missing a function
    • Advantages
      • With Mixin, you can extend functionality without any modification to the class
      • Easy to organize and maintain the division of different functional components
      • The combination of functional classes can be arbitrarily adjusted as needed
      • Can avoid creating many new classes, resulting in class inheritance confusion

Python object-oriented programming-02

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.