Ghi đè phương thức trong Python là khi bạn có hai phương thức có cùng tên, mỗi phương thức thực hiện các tác vụ khác nhau. Ghi đè phương thức là một khả năng của bất kỳ ngôn ngữ lập trình hướng đối tượng nào cho phép một lớp con hoặc lớp con cung cấp một triển khai cụ thể của một phương thức đã được cung cấp bởi một trong các lớp cha hoặc lớp cha của nó. Khi một phương thức trong lớp con có cùng tên, cùng tham số hoặc chữ ký và cùng kiểu trả về [hoặc kiểu con] như một phương thức trong siêu lớp của nó, thì phương thức trong lớp con được cho là sẽ ghi đè phương thức trong siêu lớp.
Mã nguồn
# Function Overriding class Employee: def WorkingHrs[self]: self.hrs = 50 def printHrs[self]: print["Total Working Hrs : ", self.hrs] class Trainee[Employee]: def WorkingHrs[self]: self.hrs = 60 def resetHrs[self]: super[].WorkingHrs[] employee = Employee[] employee.WorkingHrs[] employee.printHrs[] trainee=Trainee[] trainee.WorkingHrs[] trainee.printHrs[] # Reset Trainee Hrs trainee.resetHrs[] trainee.printHrs[]Để tải xuống tệp thô Bấm vào đây
đầu ra
Total Working Hrs : 50 Total Working Hrs : 60 Total Working Hrs : 50
Danh sách chương trình
Chương trình mẫu
Kết nối cơ sở dữ liệu Python
bình trăn
Hướng dẫn Python Tkinter
Ghi đè phương thức là một khái niệm của lập trình hướng đối tượng, cho phép chúng ta thay đổi cách thực hiện của một hàm trong lớp con đã được định nghĩa trong lớp cha. Đó là khả năng của một lớp con thay đổi việc triển khai bất kỳ phương thức nào đã được cung cấp bởi một trong các lớp cha [tổ tiên] của nó
Các điều kiện sau phải được đáp ứng để ghi đè một chức năng
- Kế thừa nên có. Chức năng ghi đè không thể được thực hiện trong một lớp. Chúng ta cần lấy một lớp con từ một lớp cha
- Hàm được định nghĩa lại trong lớp con phải có cùng chữ ký như trong lớp cha i. e. cùng một số tham số
Như chúng ta đã tìm hiểu về khái niệm Kế thừa, chúng ta biết rằng khi một lớp con kế thừa một lớp cha, nó cũng có quyền truy cập vào các biến và phương thức public
và protected
[access modifiers in python], ví dụ:
# parent class
class Parent:
# some random function
def anything[self]:
print['Function defined in parent class!']
# child class
class Child[Parent]:
# empty class definition
pass
obj2 = Child[]
obj2.anything[]
Hàm được định nghĩa trong lớp cha
Trong khi lớp con có thể truy cập các phương thức của lớp cha, nó cũng có thể cung cấp một triển khai mới cho các phương thức của lớp cha, được gọi là ghi đè phương thức
Ví dụ ghi đè phương thức Python
Hãy lấy một ví dụ rất thú vị mà chúng ta cũng đã có trong hướng dẫn thừa kế. Có một lớp cha tên là Animal
class Animal:
# properties
multicellular = True
# Eukaryotic means Cells with Nucleus
eukaryotic = True
# function breathe
def breathe[self]:
print["I breathe oxygen."]
# function feed
def feed[self]:
print["I eat food."]
Hãy tạo một lớp con Herbivorous
sẽ mở rộng lớp Animal
class Herbivorous[Animal]:
# function feed
def feed[self]:
print["I eat only plants. I am vegetarian."]
Trong lớp con Herbivorous
, chúng ta đã ghi đè phương thức
class Animal:
# properties
multicellular = True
# Eukaryotic means Cells with Nucleus
eukaryotic = True
# function breathe
def breathe[self]:
print["I breathe oxygen."]
# function feed
def feed[self]:
print["I eat food."]
0Vì vậy, bây giờ khi chúng ta tạo một đối tượng của lớp Herbivorous
và gọi phương thức
class Animal:
# properties
multicellular = True
# Eukaryotic means Cells with Nucleus
eukaryotic = True
# function breathe
def breathe[self]:
print["I breathe oxygen."]
# function feed
def feed[self]:
print["I eat food."]
0, phiên bản bị ghi đè sẽ được thực thi Tóm lược. trong hướng dẫn này, bạn sẽ học cách sử dụng phương thức ghi đè Python để cho phép lớp con cung cấp triển khai cụ thể của phương thức được cung cấp bởi một trong các lớp cha của nó
Giới thiệu về phương thức ghi đè Python
Phương thức ghi đè cho phép một lớp con cung cấp một triển khai cụ thể của một phương thức đã được cung cấp bởi một trong các lớp cha của nó
Hãy lấy một ví dụ để hiểu rõ hơn về phương thức ghi đè
Đầu tiên, định nghĩa lớp
8________số 8_______Code language: Python [python]
class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive
Lớp
8 có hai biến đối tượng làCode language: Python [python]
class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive
0 vàCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
1. Nó cũng có phương thứcCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
2 trả vềCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
1Code language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
Thứ hai, định nghĩa lớp
4 kế thừa từ lớpCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
8Code language: Python [python]
class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive
Code language: Python [python]
class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive
Lớp
4 có ba thuộc tính thể hiện.Code language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
0,Code language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
1 vàCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
9Code language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
Thứ ba, tạo một phiên bản mới của lớp
4 và hiển thị khoản thanh toánCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
Code language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
đầu ra
Code language: Python [python]
5000
Phương thức
2 chỉ trả vềCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
1, không phải tổng củaCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
1 và
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
Code language: Python [python]
9Code language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
Khi bạn gọi
2 từ thể hiện của lớpCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
4, Python thực thi phương thứcCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
2 của lớpCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
8, phương thức này trả vềCode language: Python [python]
class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive
1Code language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
Để đưa khoản khuyến khích bán hàng vào lương, bạn cần định nghĩa lại phương thức
2 trong lớpCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
4 như sauCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
Code language: Python [python]
class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive def get_pay[self]: return self.base_pay + self.sales_incentive
Trong trường hợp này, chúng ta nói rằng phương thức
2 trong lớpCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
4 ghi đè phương thứcCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
2 trong lớpCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
8Code language: Python [python]
class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive
Khi bạn gọi phương thức
2 của đối tượngCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
4, Python sẽ gọi phương thứcCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
2 trong lớpCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
4Code language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
Code language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
đầu ra
Code language: Python [python]
6500
Nếu bạn tạo một thể hiện của lớp
8, Python sẽ gọi phương thứcCode language: Python [python]
class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive
2 của lớpCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
8, không phải phương thứcCode language: Python [python]
class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive
2 của lớpCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
4. Ví dụCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
Code language: Python [python]
jane = Employee['Jane', 5000] print[jane.get_pay[]]
Đặt nó tất cả cùng nhau
Code language: Python [python]
class Employee: def __init__[self, name, base_pay]: self.name = name self.base_pay = base_pay def get_pay[self]: return self.base_pay class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive def get_pay[self]: return self.base_pay + self.sales_incentive if __name__ == '__main__': john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]] jane = Employee['Jane', 5000] print[jane.get_pay[]]
Ví dụ ghi đè phương thức nâng cao
Phần sau định nghĩa lớp
5Code language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
Code language: Python [python]
class Parser: def __init__[self, text]: self.text = text def email[self]: match = re.search[r'[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+', self.text] if match: return match.group[0] return None def phone[self]: match = re.search[r'\d{3}-\d{3}-\d{4}', self.text] if match: return match.group[0] return None def parse[self]: return { 'email': self.email[], 'phone': self.phone[] }
Lớp
5 có thuộc tính
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
Code language: Python [python]
7 chỉ định một đoạn văn bản sẽ được phân tích cú pháp. Ngoài ra, lớpCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
5 có ba phương thứcCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
- Phương thức
9 phân tích văn bản và trả về email
Code language: Python [python]john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
- Phương thức
0 phân tích một văn bản và trả về một số điện thoại ở định dạng
Code language: Python [python]6500
1 trong đó
Code language: Python [python]6500
2 là một số từ 0 đến 9 e. g. ,
Code language: Python [python]6500
3
Code language: Python [python]6500
- Phương thức
4 trả về một từ điển chứa hai phần tử
Code language: Python [python]6500
5 và
Code language: Python [python]6500
6. Nó gọi phương thức
Code language: Python [python]6500
9 và
Code language: Python [python]john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
0 để trích xuất email và điện thoại từ thuộc tính
Code language: Python [python]6500
7
Code language: Python [python]john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
Sau đây sử dụng lớp
5 để trích xuất email và điện thoạiCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
0Code language: Python [python]
class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive
đầu ra
1Code language: Python [python]
class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive
Giả sử bạn cần trích xuất số điện thoại ở định dạng
1, đây là định dạng số điện thoại của Vương quốc Anh. Ngoài ra, bạn muốn sử dụng email trích xuất như lớpCode language: Python [python]
jane = Employee['Jane', 5000] print[jane.get_pay[]]
5Code language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
Để làm điều đó, bạn có thể định nghĩa một lớp mới có tên là
3 kế thừa từ lớpCode language: Python [python]
jane = Employee['Jane', 5000] print[jane.get_pay[]]
5. Trong lớpCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
3, bạn override phương thứcCode language: Python [python]
jane = Employee['Jane', 5000] print[jane.get_pay[]]
0 như sauCode language: Python [python]
6500
2Code language: Python [python]
class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive
Sau đây sử dụng lớp
3 để trích xuất số điện thoại [ở định dạng Vương quốc Anh] và email từ văn bảnCode language: Python [python]
jane = Employee['Jane', 5000] print[jane.get_pay[]]
3Code language: Python [python]
class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive
đầu ra
4Code language: Python [python]
class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive
Trong ví dụ này,
8 gọi phương thứcCode language: Python [python]
jane = Employee['Jane', 5000] print[jane.get_pay[]]
4 từ lớp cha là lớp Parser. Đổi lại, phương thứcCode language: Python [python]
6500
4 gọi các phương thứcCode language: Python [python]
6500
9 vàCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
0
6500
Code language: Python [python]
Tuy nhiên,
3 không gọi phương thứcCode language: Python [python]
class Employee: def __init__[self, name, base_pay]: self.name = name self.base_pay = base_pay def get_pay[self]: return self.base_pay class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive def get_pay[self]: return self.base_pay + self.sales_incentive if __name__ == '__main__': john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]] jane = Employee['Jane', 5000] print[jane.get_pay[]]
0 của lớpCode language: Python [python]
6500
5 mà gọi phương thứcCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
0 của lớpCode language: Python [python]
6500
3Code language: Python [python]
jane = Employee['Jane', 5000] print[jane.get_pay[]]
5Code language: Python [python]
class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive
Lý do là bên trong phương thức
4,Code language: Python [python]
6500
9 làCode language: Python [python]
class Employee: def __init__[self, name, base_pay]: self.name = name self.base_pay = base_pay def get_pay[self]: return self.base_pay class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive def get_pay[self]: return self.base_pay + self.sales_incentive if __name__ == '__main__': john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]] jane = Employee['Jane', 5000] print[jane.get_pay[]]
8 là một thể hiện của lớpCode language: Python [python]
jane = Employee['Jane', 5000] print[jane.get_pay[]]
3Code language: Python [python]
jane = Employee['Jane', 5000] print[jane.get_pay[]]
Do đó, khi bạn gọi phương thức
2 bên trong phương thứcCode language: Python [python]
class Parser: def __init__[self, text]: self.text = text def email[self]: match = re.search[r'[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+', self.text] if match: return match.group[0] return None def phone[self]: match = re.search[r'\d{3}-\d{3}-\d{4}', self.text] if match: return match.group[0] return None def parse[self]: return { 'email': self.email[], 'phone': self.phone[] }
4, Python sẽ tìm kiếm phương thứcCode language: Python [python]
6500
0 được liên kết với thể hiện của phương thứcCode language: Python [python]
6500
3Code language: Python [python]
jane = Employee['Jane', 5000] print[jane.get_pay[]]
Đặt nó tất cả cùng nhau
6Code language: Python [python]
class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive
Thuộc tính ghi đè
Phần sau đây cho thấy cách triển khai các lớp Trình phân tích cú pháp và UkParser bằng cách ghi đè các thuộc tính
7Code language: Python [python]
class SalesEmployee[Employee]: def __init__[self, name, base_pay, sales_incentive]: self.name = name self.base_pay = base_pay self.sales_incentive = sales_incentive
Trong ví dụ này,
5 có biến lớpCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
7. Phương thứcCode language: Python [python]
class Parser: def __init__[self, text]: self.text = text def email[self]: match = re.search[r'[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+', self.text] if match: return match.group[0] return None def phone[self]: match = re.search[r'\d{3}-\d{3}-\d{4}', self.text] if match: return match.group[0] return None def parse[self]: return { 'email': self.email[], 'phone': self.phone[] }
0 trong lớpCode language: Python [python]
6500
5 sử dụngCode language: Python [python]
john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]
7 để trích xuất một số điện thoạiCode language: Python [python]
class Parser: def __init__[self, text]: self.text = text def email[self]: match = re.search[r'[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+', self.text] if match: return match.group[0] return None def phone[self]: match = re.search[r'\d{3}-\d{3}-\d{4}', self.text] if match: return match.group[0] return None def parse[self]: return { 'email': self.email[], 'phone': self.phone[] }
Lớp con
3 xác định lại [hoặc ghi đè] thuộc tính lớpCode language: Python [python]
jane = Employee['Jane', 5000] print[jane.get_pay[]]
7Code language: Python [python]
class Parser: def __init__[self, text]: self.text = text def email[self]: match = re.search[r'[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+', self.text] if match: return match.group[0] return None def phone[self]: match = re.search[r'\d{3}-\d{3}-\d{4}', self.text] if match: return match.group[0] return None def parse[self]: return { 'email': self.email[], 'phone': self.phone[] }
Nếu bạn gọi phương thức
4 từ thể hiện củaCode language: Python [python]
6500
3, thì phương thứcCode language: Python [python]
jane = Employee['Jane', 5000] print[jane.get_pay[]]
4 sẽ gọi phương thứcCode language: Python [python]
6500
0 sử dụng phương thứcCode language: Python [python]
6500
7 được định nghĩa trong lớpCode language: Python [python]
class Parser: def __init__[self, text]: self.text = text def email[self]: match = re.search[r'[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+', self.text] if match: return match.group[0] return None def phone[self]: match = re.search[r'\d{3}-\d{3}-\d{4}', self.text] if match: return match.group[0] return None def parse[self]: return { 'email': self.email[], 'phone': self.phone[] }
3Code language: Python [python]
jane = Employee['Jane', 5000] print[jane.get_pay[]]