class Child(Parent)
super().method()
__init__
)有所變動(跟父類不同),則需要使用 super().__init__()
或 父類別.__init__()
來引用父類別的 __init__
=
),則會新增物件變數,可參考之前的class variables(類別變數)
class M():
z = "Z"
def __init__(self):
self.m = "M"
class C(M):
pass
class D(M):
def __init__(self):
# D 自己的 __init__
# 沒有 self.m
self.d = "D"
class E(M):
def __init__(self):
super().__init__()
# M.__init__()
# 引用父類別 M 的 __init__
# 有 self.m
self.e = "E"
c = C()
d = D()
e = E()
print(c.m)
# M
print(d.d)
# D
print(d.m)
# 'D' object has no attribute 'm'
# 跳錯,並無 M() 內的 m
print(e.m)
# M
# 有引入 M() 內的 m
print(e.e)
# E
# 類別變數
print(c.z, d.z, e.z)
# Z Z Z
# 繼承至 M
C.z = "C class"
# 新建類別變數 z
print(c.z, C.z)
# C class C class
c.z = "C obj"
# 新建物件變數 z
print(c.z, C.z)
# C obj C class
class C(B, A)
class A():
val = "is a"
def print_val(self):
print("A")
class B():
def print_val(self):
print("B")
class C(B, A):
pass
c = C()
c.print_val()
# B
print(c.val)
# is a
class A():
def print_a(self):
print("A")
class B(A):
b = "b"
pass
class C(B):
pass
c = C()
c.print_a()
# A
print(c.b)
# b
類別竟然還有一些內容沒提到!明天繼續