July 25, 2019 class inheritance 1

  Oriented on the image: inheritance, polymorphism, encapsulation

class ParentClass1:
    pass

class ParentClass2:
    pass

class SubClass(ParentClass1):#单继承
    pass

class SubClass2(ParentClass1,ParentClass2):#多继承
    pass

 

Subclass defined attributes If you drink the same name as the parent class property, the priority call subclass does not cover the said

 

When inheritance:

1. When a class is significantly different, and a small component of a larger class of things needed by the class, with the combination.

2. When there are many of the same functional class, these common features extracted made base class inheritance.

 

Inheritance also has two meanings:

1. Inheritance and derived: code reuse is reduced. (Not independent, not recommended)

2. Statement subclasses compatible with a base class defines an interface class, subclass inherits the interface class and the method defined in the interface implementation. (Vip recommended)

class Dad: 
    Money = 10
     DEF  the __init__ (Self, name):
         Print ( ' Dad ' ) 
        the self.name = name 

    DEF hit_son (Self):
         Print ( ' % S is Son HIT ' % the self.name) 

class Son (Dad) : 
    Money = 55 # priority call subclass, but not covering 


S1 = son ( ' SXJ ' ) # properties methods inherited class dad's son, there is a need to pass parameters dad name 
Print (s1.money, s1.name, Dad.money ) 
s1.hit_son ()

》》》》

DAD
55 SXJ 10
SXJ being hit son

 

 

Interface inheritance: normalized design. Make a good abstraction, which provides a compatible interface.

Import ABC # interface inheritance plays force limiting subclass 
class All_file (= the metaclass that abc.ABCMeta): # interface inheritance: the definition of the parent class, must have a predetermined read and write methods, the parent may not be implemented, but it must be subclasses there are these two methods 
    @ abc.abstractclassmethod # below but abstract methods (mandatory subclass must have read and write methods) 
    DEF read (Self):
         Pass 

    DEF write (Self):
         Pass 


class Disk (All_file):
     DEF read (Self) :
         Print ( ' Disk Read ' )
     DEF Write (Self):
         Print ( ' Disk Write ' ) 

class CDrom (All_file):
    pass

class Mem(All_file):
    pass

d1=Disk()
d1.read()
d1.write()

》》》

Disk read
Disk write

Guess you like

Origin www.cnblogs.com/python1988/p/11246648.html