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()

此外,還有多重繼承等方法,使用時優先考慮最近的類。

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