python class繼承


https://blog.csdn.net/brucewong0516/article/details/79121179

類繼承:

class SubClassName(parentClass,[,parentClass2,..]):
        class_suite

實現繼承之后,子類將繼承父類的屬性,也可以使用內建函數insubclass()來判斷一個類是不是另一個類的子孫類

issubclass(Child, Parent),其中,child和parent都是class,child繼承parent

class Parent(object):
    '''
    parent class
    '''
    numList = []
    def numdiff(self, a, b):
        return a-b

class Child(Parent):
    pass


c = Child()    
# subclass will inherit attributes from parent class 
#子類繼承父類的屬性   
Child.numList.extend(range(10))
print(Child.numList)

print("77 - 2 =", c.numdiff(77, 2))

# built-in function issubclass() 
print(issubclass(Child, Parent))
print(issubclass(Child, object))

# __bases__ can show all the parent classes
#bases屬性查看父類
print('the bases are:',Child.__bases__)

# doc string will not be inherited
#doc屬性不會被繼承
print(Parent.__doc__)
print(Child.__doc__)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
77 - 2 = 75
True
True
the bases are: (<class '__main__.Parent'>,)

    parent class

None

super的使用詳解

  • super主要來調用父類方法來顯示調用父類,在子類中,一般會定義與父類相同的屬性(數據屬性,方法),從而來實現子類特有的行為。也就是說,子類會繼承父類的所有的屬性和方法,子類也可以覆蓋父類同名的屬性和方法
class Parent(object):
    Value = "Hi, Parent value"
    def fun(self):
        print("This is from Parent")
#定義子類,繼承父類               
class Child(Parent):
    Value = "Hi, Child  value"
    def ffun(self):
        print("This is from Child")
c = Child()    
c.fun()
c.ffun()
print(Child.Value)
This is from Parent
This is from Child
Hi, Child value

但是,有時候可能需要在子類中訪問父類的一些屬性,可以通過父類名直接訪問父類的屬性,當調用父類的方法是,需要將”self”顯示的傳遞進去的方式

class Parent(object):
    Value = "Hi, Parent value"
    def fun(self):
        print("This is from Parent")

class Child(Parent):
    Value = "Hi, Child  value"
    def fun(self):
        print("This is from Child")
        Parent.fun(self)   #調用父類Parent的fun函數方法

c = Child()    
c.fun()
This is from Child
This is from Parent  #實例化子類Child的fun函數時,首先會打印上條的語句,再次調用父類的fun函數方法

這種方式有一個不好的地方就是,需要經父類名硬編碼到子類中,為了解決這個問題,可以使用Python中的super關鍵字:

class Parent(object):
    Value = "Hi, Parent value"
    def fun(self):
        print("This is from Parent")

class Child(Parent):
    Value = "Hi, Child  value"
    def fun(self):
        print("This is from Child")
        #Parent.fun(self)
        super(Child,self).fun()  #相當於用super的方法與上一調用父類的語句置換

c = Child()    
c.fun()
This is from Child
This is from Parent  #實例化子類Child的fun函數時,首先會打印上條的語句,再次調用父類的fun函數方法
對於所有的類,都有一組特殊的屬性
_ _ name_ _:類的名字(字符串)
_ _ doc _ _ :類的文檔字符串
_ _ bases _ _:類的所有父類組成的元組
_ _ dict _ _:類的屬性組成的字典
_ _ module _ _:類所屬的模塊
_ _ class _ _:類對象的類型

copy from https://blog.csdn.net/brucewong0516/article/details/79121179


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM