共計(jì) 738 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
Python 中子類可以通過繼承父類來繼承父類的屬性??梢允褂?super()
函數(shù)來調(diào)用父類的構(gòu)造函數(shù),從而繼承父類的屬性。以下是一個(gè)示例代碼:
class ParentClass:
def __init__(self, attribute):
self.attribute = attribute
class ChildClass(ParentClass):
def __init__(self, attribute, child_attribute):
super().__init__(attribute) # 調(diào)用父類的構(gòu)造函數(shù)
self.child_attribute = child_attribute
parent = ParentClass("Parent Attribute")
child = ChildClass("Parent Attribute", "Child Attribute")
print(parent.attribute) # 輸出 "Parent Attribute"
print(child.attribute) # 輸出 "Parent Attribute"
print(child.child_attribute) # 輸出 "Child Attribute"
在上面的代碼中,ParentClass
是父類,ChildClass
是子類。子類 ChildClass
繼承了父類 ParentClass
的屬性 attribute
。在子類的構(gòu)造函數(shù)中,我們使用 super().__init__(attribute)
來調(diào)用父類的構(gòu)造函數(shù)并初始化父類的屬性。然后,我們還可以在子類中定義自己的屬性,如 child_attribute
。最后,我們創(chuàng)建父類實(shí)例 parent
和子類實(shí)例 child
,并分別訪問它們的屬性。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完