Inheritance (Kế thừa)
Là ngôn ngữ OOP, Python hỗ trợ kế thừa, thậm chí multiple inheritance. Class có thể kế thừa từ class khác. Class con (subclass/heir/child) kế thừa attribute và behavior method từ superclass. Kế thừa = định nghĩa class mới với ít hoặc không sửa đổi class hiện có.
class A: pass
class B: pass
class C(A, B): # subclass của A và B (multiple inheritance)
pass
Instantiation (Khởi tạo instance)
Instantiate class = tạo bản sao của class, kế thừa tất cả class variable và method. Instantiate Python class đơn giản: gọi class như function, truyền argument cho __init__. Return value là object mới tạo.
Ví dụ
class Foo:
def __init__(self, x, y):
print(x + y)
f = Foo(3, 4)
Output
7