Python class III (three characteristics, constraints, Super)

1. Content Today

  1. Object-oriented three properties: encapsulation, inheritance, polymorphism
  2. What is inherited?
  3. Inherited advantages
  4. Single inheritance, multiple inheritance
  5. Constraint class
  6. super-depth understanding

2. Specific contents

  1. Object-oriented three properties: encapsulation, inheritance, polymorphism

    • Package

      • The contents of something attached to a place, and can be taken out
      • Class, set the static property set methods
      • Objects, attributes may be packaged in its object space
    • Polymorphism

      • A thing produce a variety of forms
      • Various status data structure. Such as a variable, which can be copied into a list may be assigned to a string
        • Remark: In languages ​​such as C ++ or Java, the definition of variables must be declared in advance the types of variables, otherwise it will error
    • inherit

  2. What is inherited?

    • Professional point of view: B inherits Class A, B is called a subclass of A, derived class, called B A parent base class, superclass
    • Subclass can call all the methods and properties of the parent class
  3. Inherited advantages

    • Save code
    • Enhanced coupling
    • Code normative
  4. Single inheritance, multiple inheritance

    1. Single inheritance: Only one parent

      • Class name from the parent class attributes and methods performed
      • Performing parent class attributes and methods from the object
      class Animal():
      
        live = '有生命的'
      
        def __init__(self,name,age,sex):
          self.name = name
          self.age = age
          self.sex = sex
      
        def eat(self):
          print(f'self-->{self}')
          print('动物都需要吃饭')
      
      class Person(Animal):
        pass
      
      
      print(Person.__dict__)
      print(Person.live)
      Person.eat('xxx')
      
      p1 = Person('jik',18,'boy')
      print(p1.live)
      
      p1.eat()
      print(f'p1-->{p1}')
      
      Person.live = 'xxx'
      print(Person.live)

      Output:

      {'__module__': '__main__', '__doc__': None}
      有生命的
      self-->xxx
      动物都需要吃饭
      有生命的
      self--><__main__.Person object at 0x104634ac8>
      动物都需要吃饭
      p1--><__main__.Person object at 0x104634ac8>
      xxx

      Remark:

      • Subclass and subclass object can call the parent class's attributes and methods, can not be operated (additions and deletions)
      • When the method of the child and parent class of the same name, parent class will subclass of 'cover'
      class Animal():
      
        live = '有生命的'
      
        def __init__(self,name,age,sex):
          self.name = name
          self.age = age
          self.sex = sex
      
        def eat(self):
          print(f'self-->{self}')
          print('动物都需要吃饭')
      
      class Person(Animal):
      
        def eat(self):
          print('人类需要吃饭')
      
      p1 = Person('jik',18,'boy')
      p1.eat()#人类需要吃饭

      Remark:

      • Cis meet the same object lookup 'nearest' principle, and sequentially irreversible single

      Needs to be performed immediately when the parent class and method of performing the method subclass, are required in the method of the same name of the object class where the 'salt'

      • There are two solutions
      class Animal():
      
        live = '有生命的'
      
        def __init__(self,name,age,sex):
          self.name = name
          self.age = age
          self.sex = sex
      
        def eat(self):
          print(f'self-->{self}')
          print('动物都需要吃饭')
      
      class Person(Animal):
      
        def __init__(self,name,age,sex,hobby):
      
          #方法一:
          Animal.__init__(self,name,age,sex)
      
          #方法二:
          super(Person,self).__init__(name,age,sex)
          super().__init__(name,age,sex)
          self.hobby = hobby
      
        def eat(self):
          print('人类都需要吃饭')
          super().eat()
      
      p1 = Person('jik',18,'boy','打球')
      p1.eat()
      
      
      人类都需要吃饭
      self--><__main__.Person object at 0x10d0d7b00>
      动物都需要吃饭
    2. Multiple inheritance: the presence of two or more parent classes

      • Classic: not inherit all the parent class object, depth-first algorithm is based on a query rule
        • python2.2 previous versions
      • The new class: default inherit all the parent class object, query rules mro algorithms (topological sorting) basis
        • Python3.0 and later
      • coexist:
        • Python2.2 ~ 2.7 version
  5. Constraint class

    • Ducks Type: two separate classes, there are naming the same similar functions, python will be developed in the ground floor of a specification that enables these functions unity, saying the two classes each other duck categories:
    class Str:
      def index(self):
        pass
      def count(self):
        pass
    
    class list:
      def index(self):
        pass
      def count(self):
        pass
    • Constraint class: the development of a standardized, unified coding, an exception is thrown into irregularities in the classes and methods

      • The first method: raise

      class Payment:
      
        def pay(self,money):  #约定俗称定义一种规范,子类要定义pay方法
          raise Exception('子类必须定义此方法')
      
      class QQpay(Payment):
      
        def pay(self,money):
          print(f'利用qq支付了{money}')
      
      
      class Alipay(Payment):
      
        def pay(self,money):
          print(f'利用支付宝支付了{money}')
      
      class Wechatpay(Payment):
      
        def pay(self,money):
          print(f'利用微信支付了{money}')
       /////////////////////////////////   
       /def fukuan(self,money):        /
       / print(f'利用微信支付了{money}') /
      
      def pay(obj,money):
        obj.pay(money)
      
      obj = Wechatpay()
      pay(obj,300)
      
      obj.fukuan(300)#报错(‘子类必须定义此方法’)
      • The second method: introducing and fixing type fixing method of fixing abc

      from abc import ABCMeta, abstractmethod
      
      class Payment(metaclass=ABCMeta):
      
          @abstractmethod
          def pay(self, money):
              pass
      
      class QQpay(Payment):
      
          def pay(self, money):
              print(f'利用qq支付了{money}')
      
      
      class Alipay(Payment):
      
          def pay(self, money):
              print(f'利用支付宝支付了{money}')
      
      class Wechatpay(Payment):
          def fuqian(self,money):
              print(f'利用微信支付了{money}')
      
      
      obj3 = Wechatpay()

      Output:

      报错("Can't instantiate abstract class Wechatpay with abstract methods pay")
  6. super-depth understanding

    • super (): method performed parent class, brackets two parameters, the first parameter is any sequence mro object is located in one element (including the present class name), the second parameter is the self, it will execute this mro sequence, the first parameter (s) of the next class
    class A:
      def f1(self):
        print('in A')
    
    class Foo:
      def f1(self):
        print('in B')
    
    class Bar(A):
      def f1(self):
        print('in Bar')
    
    calss Info(Foo,Bar):
      def f1(self):
        super(Info,self).f1()
        super(Foo,self).f1()
        super(Bar,self).f1()
        print('in Info f1')
    
    
    obj = Info()
    print(Info.mro())
    obj.f1()

    Output:

    [<class '__main__.Info'>, <class '__main__.Foo'>, <class '__main__.Bar'>, <class '__main__.A'>, <class 'object'>]
    in B
    in Bar
    in A
    in Info f1

Guess you like

Origin www.cnblogs.com/xiaohei-chen/p/12093492.html