OOP Python – Kế thừa trong Python

22/02/2023 - lượt xem
Chia sẻ
 
Rate this post

Trong bài viết trước chúng ta đã tìm hiểu cơ bản về OOP trong Python. Chúng ta cũng đã biết về Kế thừa với Python, trong bài viết này sẽ làm rõ hơn về những khái niệm xung quanh việc kế thừa của Python.

Thông tin cơ bản về Kế thừa trong Python

Một trong những lợi thế của Lập trình hướng đối tượng là khả năng tái sử dụng. Kế thừa là một trong các cơ chế để đảm bảo điều này. Trong kế thừa thì một class (thường được gọi là class cha – super class) thì được kế thừa bởi 1 class khác (class con).

Class con có thể thêm vào các thuộc tính so với class cha.

Ví dụ dưới đây cho bạn hiểu về cách xây dựng class kế thừa trong Python.

# A Python program to demonstrate inheritance

# Base or Super class. Note object in bracket.
# (Generally, object is made ancestor of all classes)
# In Python 3.x "class Person" is
# equivalent to "class Person(object)"
class Person(object):
	
	# Constructor
	def __init__(self, name):
		self.name = name

	# To get name
	def getName(self):
		return self.name

	# To check if this person is employee
	def isEmployee(self):
		return False


# Inherited or Sub class (Note Person in bracket)
class Employee(Person):

	# Here we return true
	def isEmployee(self):
		return True

# Driver code
emp = Person("Geek1") # An Object of Person
print(emp.getName(), emp.isEmployee())

emp = Employee("Geek2") # An Object of Employee
print(emp.getName(), emp.isEmployee())

Kết quả

('Geek1', False)
('Geek2', True)

Cách kiểm tra một class là class con của class khác như thế nào?

Python cung cấp hàm issubclass() cho phép biết 1 class có phải class con của class khác hay không.

# Python example to check if a class is
# subclass of another

class Base(object):
	pass # Empty Class

class Derived(Base):
	pass # Empty Class

# Driver Code
print(issubclass(Derived, Base))
print(issubclass(Base, Derived))

d = Derived()
b = Base()

# b is not an instance of Derived
print(isinstance(b, Derived))

# But d is an instance of Base
print(isinstance(d, Base))

Tham số đầu tiên của hàm issubclass có thể nhận vào là tên class, nếu bạn muốn kiểm tra 1 đối tượng, sử dụng hàm isintance.

Kết quả

True
False
False
True

Object class trong Python

Cũng giống như class Object trong Java, trong Python (kể từ phiên bản 3.x) thì object là nguồn gốc của mọi class khác.

Trong Python 3.x thì class Test(object) và class Test thì đều như nhau

Test(object) nghĩa là class Test được kế thừa object

Trong Python 2.x thì “class Test(object)” tạo ra 1 class với object là cha (gọi theo phong cách class mới) và “class Test” được tạo theo phong cách class cũ (không có object là cha)

Python hỗ trợ đa kế thừa?

Không giống như Java và C++, Python hỗ trợ đa kế thừa. Các class cha được phân biệt nhau bởi dấu “,”.

# Python example to show working of multiple
# inheritance
class Base1(object):
	def __init__(self):
		self.str1 = "Geek1"
		print "Base1"

class Base2(object):
	def __init__(self):
		self.str2 = "Geek2"		
		print "Base2"

class Derived(Base1, Base2):
	def __init__(self):
		
		# Calling constructors of Base1
		# and Base2 classes
		Base1.__init__(self)
		Base2.__init__(self)
		print "Derived"
		
	def printStrs(self):
		print(self.str1, self.str2)
		

ob = Derived()
ob.printStrs()

Kết quả

Base1
Base2
Derived
('Geek1', 'Geek2')

Làm thế nào để truy cập thuộc tính class cha từ class con

Sử dụng thông qua tên class cha

# Python example to show that base
# class members can be accessed in
# derived class using base class name
class Base(object):

	# Constructor
	def __init__(self, x):
		self.x = x	

class Derived(Base):

	# Constructor
	def __init__(self, x, y):
		Base.x = x
		self.y = y

	def printXY(self):
	
	# print(self.x, self.y) will also work
	print(Base.x, self.y)


# Driver Code
d = Derived(10, 20)
d.printXY()

Kết quả

(10, 20)

Sử dụng super()

# Python example to show that base
# class members can be accessed in
# derived class using super()
class Base(object):

	# Constructor
	def __init__(self, x):
		self.x = x	

class Derived(Base):

	# Constructor
	def __init__(self, x, y):
		
		''' In Python 3.x, "super().__init__(name)"
			also works'''
		super(Derived, self).__init__(x)
		self.y = y

	def printXY(self):

	# Note that Base.x won't work here
	# because super() is used in constructor
	print(self.x, self.y)


# Driver Code
d = Derived(10, 20)
d.printXY()

Kết quả

(10, 20)

 

 

    Liên hệ với chúng tôi

    Để lại thông tin để nhận được các bài viết khác

    Rate this post

    Xem thêm nhiều bài tin mới nhất về Odoo

    Xem thêm