@override trong Python là gì?

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

  1. 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
  2. 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 publicprotected[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."]
0

Vì 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

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]
8

________số 8_______

Lớp

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]
8 có hai biến đối tượng là

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
0 và

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
1. Nó cũng có phương thức

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
2 trả về

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
1

Thứ hai, định nghĩa lớp

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
4 kế thừa từ lớp

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]
8

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]

Lớp

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
4 có ba thuộc tính thể hiện.

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
0,

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
1 và

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
9

Thứ ba, tạo một phiên bản mới của lớp

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
4 và hiển thị khoản thanh toán

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]

đầu ra

5000

Code language: Python [python]

Phương thức

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
2 chỉ trả về

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
1, không phải tổng của

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
1 và

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
9

Khi bạn gọi

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
2 từ thể hiện của lớp

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
4, Python thực thi phương thức

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
2 của lớp

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]
8, phương thức này trả về

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
1

Để đư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

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
2 trong lớp

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
4 như sau

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

Code language: Python [python]

Trong trường hợp này, chúng ta nói rằng phương thức

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
2 trong lớp

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
4 ghi đè phương thức

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
2 trong lớp

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]
8

Khi bạn gọi phương thức

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
2 của đối tượng

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
4, Python sẽ gọi phương thức

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
2 trong lớp

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
4

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]

đầu ra

6500

Code language: Python [python]

Nếu bạn tạo một thể hiện của lớp

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]
8, Python sẽ gọi phương thức

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
2 của lớp

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]
8, không phải phương thức

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
2 của lớp

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
4. Ví dụ

jane = Employee['Jane', 5000] print[jane.get_pay[]]

Code language: Python [python]

Đặt nó tất cả cùng nhau

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[]]

Code language: Python [python]

Ví dụ ghi đè phương thức nâng cao

Phần sau định nghĩa lớp

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
5

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[] }

Code language: Python [python]

Lớp

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
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ớp

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
5 có ba phương thức

  • Phương thức

    john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

    Code language: Python [python]
    9 phân tích văn bản và trả về email
  • Phương thức

    6500

    Code language: Python [python]
    0 phân tích một văn bản và trả về một số điện thoại ở định dạng

    6500

    Code language: Python [python]
    1 trong đó

    6500

    Code language: Python [python]
    2 là một số từ 0 đến 9 e. g. ,

    6500

    Code language: Python [python]
    3
  • Phương thức

    6500

    Code language: Python [python]
    4 trả về một từ điển chứa hai phần tử

    6500

    Code language: Python [python]
    5 và

    6500

    Code language: Python [python]
    6. Nó gọi phương thức

    john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

    Code language: Python [python]
    9 và

    6500

    Code language: Python [python]
    0 để trích xuất email và điện thoại từ thuộc tính

    john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

    Code language: Python [python]
    7

Sau đây sử dụng lớp

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
5 để trích xuất email và điện thoại

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]
0

đầu ra

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]
1

Giả sử bạn cần trích xuất số điện thoại ở định dạng

jane = Employee['Jane', 5000] print[jane.get_pay[]]

Code language: Python [python]
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ớp

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
5

Để làm điều đó, bạn có thể định nghĩa một lớp mới có tên là

jane = Employee['Jane', 5000] print[jane.get_pay[]]

Code language: Python [python]
3 kế thừa từ lớp

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
5. Trong lớp

jane = Employee['Jane', 5000] print[jane.get_pay[]]

Code language: Python [python]
3, bạn override phương thức

6500

Code language: Python [python]
0 như sau

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]
2

Sau đây sử dụng lớp

jane = Employee['Jane', 5000] print[jane.get_pay[]]

Code language: Python [python]
3 để trích xuất số điện thoại [ở định dạng Vương quốc Anh] và email từ văn bản

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]
3

đầu ra

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]
4

Trong ví dụ này,

jane = Employee['Jane', 5000] print[jane.get_pay[]]

Code language: Python [python]
8 gọi phương thức

6500

Code language: Python [python]
4 từ lớp cha là lớp Parser. Đổi lại, phương thức

6500

Code language: Python [python]
4 gọi các phương thức

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
9 và

6500

Code language: Python [python]
0

Tuy nhiên,

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[]]

Code language: Python [python]
3 không gọi phương thức

6500

Code language: Python [python]
0 của lớp

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
5 mà gọi phương thức

6500

Code language: Python [python]
0 của lớp

jane = Employee['Jane', 5000] print[jane.get_pay[]]

Code language: Python [python]
3

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]
5

Lý do là bên trong phương thức

6500

Code language: Python [python]
4,

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[]]

Code language: Python [python]
9 là

jane = Employee['Jane', 5000] print[jane.get_pay[]]

Code language: Python [python]
8 là một thể hiện của lớp

jane = Employee['Jane', 5000] print[jane.get_pay[]]

Code language: Python [python]
3

Do đó, khi bạn gọi phương thức

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[] }

Code language: Python [python]
2 bên trong phương thức

6500

Code language: Python [python]
4, Python sẽ tìm kiếm phương thức

6500

Code language: Python [python]
0 được liên kết với thể hiện của phương thức

jane = Employee['Jane', 5000] print[jane.get_pay[]]

Code language: Python [python]
3

Đặt nó tất cả cùng nhau

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]
6

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

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]
7

Trong ví dụ này,

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
5 có biến lớp

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[] }

Code language: Python [python]
7. Phương thức

6500

Code language: Python [python]
0 trong lớp

john = SalesEmployee['John', 5000, 1500] print[john.get_pay[]]

Code language: Python [python]
5 sử dụng

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[] }

Code language: Python [python]
7 để trích xuất một số điện thoại

Lớp con

jane = Employee['Jane', 5000] print[jane.get_pay[]]

Code language: Python [python]
3 xác định lại [hoặc ghi đè] thuộc tính lớp

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[] }

Code language: Python [python]
7

Nếu bạn gọi phương thức

6500

Code language: Python [python]
4 từ thể hiện của

jane = Employee['Jane', 5000] print[jane.get_pay[]]

Code language: Python [python]
3, thì phương thức

6500

Code language: Python [python]
4 sẽ gọi phương thức

6500

Code language: Python [python]
0 sử dụng phương thức

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[] }

Code language: Python [python]
7 được định nghĩa trong lớp

jane = Employee['Jane', 5000] print[jane.get_pay[]]

Code language: Python [python]
3

Ghi đè được sử dụng để làm gì?

Về mặt kỹ thuật, ghi đè là một hàm yêu cầu một lớp con hoặc lớp con cung cấp nhiều cách triển khai 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ó, trong bất kỳ . .

@override nghĩa là gì trong mã Java?

Chú thích @Override @Override thông báo cho trình biên dịch rằng phần tử này dùng để ghi đè lên một phần tử được khai báo trong một lớp cha . Các phương thức ghi đè sẽ được thảo luận trong Giao diện và Kế thừa.

Ghi đè có nghĩa là gì trong mã?

Ghi đè có nghĩa là gì?

Chủ Đề