Python類super()及私有屬性原理解析
super()有參數寫法:
# 1.定義父類class A(object): def __init__(self): self.num = 1 def info_print(self): print(self.num)class C(A): def __init__(self): self.num = 2 def info_print(self): print(self.num) super(C, self).__init__() super(C, self).info_print()# 2. 定義子類,繼承父類class B(C): def __init__(self): self.num = 3 def info_print(self): self.__init__() print(self.num) def print_A(self): A.__init__(self) A.info_print(self) def print_C(self): C.__init__(self) C.info_print(self) def print_AC(self): super(B, self).__init__() super(B, self).info_print()b = B()b.print_AC()
super()用于調用父類的方法
無參寫法:
super().__init__()super().info_print()
使用super()方法可以自動查找父類,查找順序遵循__mro__類屬性的順序
私有屬性與方法
設置私有極限的方法:在屬性名和方法名前面加上兩個下劃線__
設置之后設置的實例屬性或實例方法不繼承給子類
獲取和修改私有屬性:
在類中添加函數:
def get_money(self): return self.__moneydef set_money(self, money): self.__money = money
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: