A succession:
The purpose is to save inheritance code. When the two classes have something in common, we need to inherit
class Syy (): Country = ' China ' DEF the __init__ (Self): self.money = 5000 DEF chaogu (Self): self.money + = 50000 Print ( ' stock S% ' % self.money) class Xs (Syy) # Inheritance: subclasses (parent), the method of the parent class, subclass have. A plurality of parent classes inherit inheritable DEF chaogu (Self): Print ( ' stock, singing ' , self.money) # Money inherited Money: 5000 500 self.money = # method overrides the parent class. Method overrides Print ( " money rewritten S% " % self.money) # money is money rewritten: 500 # . Super () method XXX XXX find the parent class, and instantiate it (ie call). It may be used to make changes on the basis of the parent class. Parameters of the original parent class still pass parameters: . Super () chaogu () SDB = Xs () sdb.chaogu ()
Second, the example
class BaseDB: DEF the __init__ (Self, IP, Port, password, DB): self.ip = IP self.port = Port self.password = password self.db = DB class the MySQL: DEF the __init__ (Self, IP, User, Port , password, DB): # definition of the parameter values to be passed . Super () the __init__ (IP, Port, password, DB) # inherits the base class, the base class and pass the required parameters self.user = User # when a parent needs class function, and when necessary supplement, use super () to inherit the parent class Redis (BaseDB): DEFConn (Self): self.r = redis.Redis (= Host self.ip, DB = self.db, password = self.password) # when the value of the base class requires exactly the same, no supplement, it is possible not super ()
Third, the order of succession when multiple inheritance
When a class inherits a plurality of classes, the order of succession:
class A (Object): # python2 the new class, equivalent to python3 in class A: DEF say (Self): Print ( ' A ' ) class B (A): # Pass DEF say (Self): Print ( ' B ' ) class C (A): Pass # DEF say (Self): # Print (' C ') class D (C, B): Pass D = D () d.say () Print (D.mro () ) # View the order of succession #[<class '__main __. D '>, <class '__main __. C'>, <class '__main __. B'>, <class '__main __. A'>, <class 'object'>] # breadth first # [< class '__main __. D'> , <class '__main __. C'>, <class '__main __. A'>, <class '__main __. B'>, <class 'object'>] depth First # Python 2 in the depth-first # the new class of breadth-first python3 or python2