Python之类继承与多态

1.类的一般调用

#以下用Python3

#参考:https://www.cnblogs.com/python-nameless/p/6229506.html

#补充参考:https://blog.csdn.net/oschina_41675984/article/details/80373587

class Base(object):#定义基层类
    def __init__(self):
        print('Base create')
 
class childA(Base):#显式继承
    def __init__(self):
        print('creat A '),
        Base.__init__(self)
 
 
class childB(Base):#显式继承
    def __init__(self):
        print('creat B '),
        super(childB, self).__init__() #super表明本类继承上一级类的初始化,使用时本类必须有继承
 
base = Base()
 
a = childA()
b = childB()

以下为结果:

2.类的嵌套调用:

 

class Base(object):
    def __init__(self):
        print ('Base create')
 
class childA(Base):
    def __init__(self):
        print ('enter A ')
        # Base.__init__(self)
        super(childA, self).__init__()
        print ('leave A')
class childB(Base):
    def __init__(self):
        print ('enter B ')
        # Base.__init__(self)
        super(childB, self).__init__()
        print ('leave B')
 
class childC(childA, childB):
    pass
 
aa=childC()

运行结果:

enter A 
enter B 
Base create
leave B
leave A

#上述代码中的childC调用很有特点

3.类的多态

3.1 用于判断类的类型的函数

Python 有两个判断继承的函数:isinstance() 用于检查实例类型;issubclass() 用于检查类继承。

#参考https://www.cnblogs.com/feeland/p/4419121.html

class Person(object):
    pass

class Child(Person):                 # Child 继承 Person
    pass

May = Child()
Peter = Person()    

print(isinstance(May,Child))         # True
print(isinstance(May,Person))        # True
print(isinstance(Peter,Child))       # False
print(isinstance(Peter,Person))      # True
print(issubclass(Child,Person))      # True

3.2 类的多态实现

可以对类在继承的同时,进行修改,以创建新类。

class Person(object):
    def __init__(self,name,sex):
        self.name = name
        self.sex = sex
        
    def print_title(self):
        if self.sex == "male":
            print("man")
        elif self.sex == "female":
            print("woman")

class Child(Person):                # Child 继承 Person
    def print_title(self):
        if self.sex == "male":
            print("boy")
        elif self.sex == "female":
            print("girl")
        
May = Child("May","female")
Peter = Person("Peter","male")

print(May.name,May.sex,Peter.name,Peter.sex)
May.print_title()
Peter.print_title()

此外,还有多重继承等方法,使用时优先考虑最近的类。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章