Trong bài viết này, chúng ta sẽ khám phá khái niệm ghi đè trong Python. Chúng ta cũng sẽ khám phá các phương thức ma thuật và các lớp trừu tượng là gì
Giới thiệu
Ghi đè là một khái niệm thú vị trong lập trình hướng đối tượng. Khi các định nghĩa phương thức của Lớp cơ sở được thay đổi trong Lớp con [Dẫn xuất], điều này được gọi là ghi đè phương thức. Bạn đang giữ nguyên chữ ký của phương thức nhưng thay đổi định nghĩa hoặc triển khai phương thức được xác định bởi một trong các tổ tiên. Không có cú pháp đặc biệt hoặc từ khóa bổ sung cần thiết để thực hiện ghi đè phương thức trong Python. Đây là một khái niệm lập trình hướng đối tượng rất quan trọng vì nó làm cho tính kế thừa khai thác hết sức mạnh của nó. Về bản chất, bạn không sao chép mã, do đó tuân theo nguyên tắc lập trình DRY [không lặp lại chính bạn] và bạn có thể nâng cao phương thức trong lớp con
Để hiểu khái niệm ghi đè, bạn phải biết các khái niệm cơ bản của lập trình hướng đối tượng như lớp và kế thừa. Có rất nhiều tài nguyên trên internet về OOP. Một tài nguyên thực sự tốt là lớp Python hướng đối tượng của Học viện Finxter. https. //học viện. người tài chính. com/đại học/hướng đối tượng-python/
Cần ghi đè
Trong ví dụ sau, bạn sẽ thấy cách hoạt động của tính kế thừa và vấn đề không ghi đè một phương thức trong lớp con. Lớp Parent có một phương thức
#Overriding class Parent[]: def whoami[self]: print["I am a parent"] class Child[Parent]: def play[self]: print[" I am playing"] def whoami[self]: print["I am a child"] parent = Parent[] parent.whoami[] print[] child = Child[] child.whoami[] # Output: # I am a parent # I am a child8 hiển thị
#Overriding class Parent[]: def whoami[self]: print["I am a parent"] class Child[Parent]: def play[self]: print[" I am playing"] def whoami[self]: print["I am a child"] parent = Parent[] parent.whoami[] print[] child = Child[] child.whoami[] # Output: # I am a parent # I am a child9. Phương thức này được kế thừa bởi lớp
class Employee[]: def __init__[self, empno, ename, salary, deptno]: self.Empno = empno self.Ename = ename self.Salary = salary self.Deptno = deptno def showEmployee[self]: print["Employee # : {}\nEmployee Name : {}\nSalary : {}\nDepartment : {}".format[self.Empno, self.Ename, self.Salary, self.Deptno]] class Salesman[Employee]: def __init__[self, empno, ename, salary, deptno, comm]: self.Commission = comm super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["Salesman Profile"] super[].showEmployee[] print["Commision : ", self.Commission] class CEO[Employee]: def __init__[self, empno, ename, salary, deptno, stock]: self.Stock = stock super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["CEO Profile"] super[].showEmployee[] print["Stock Options : ", self.Stock] salesman = Salesman[200, "John Doe", 67000, "Sales", 100] salesman.showEmployee[] print[""] ceo = CEO[40, "Jennifer Smith", 300000, "Director", 1000000] ceo.showEmployee[]0. Gọi phương thức
#Overriding class Parent[]: def whoami[self]: print["I am a parent"] class Child[Parent]: def play[self]: print[" I am playing"] def whoami[self]: print["I am a child"] parent = Parent[] parent.whoami[] print[] child = Child[] child.whoami[] # Output: # I am a parent # I am a child8 từ lớp Con, gọi phương thức được kế thừa từ lớp Cha và do đó hiển thị
#Overriding class Parent[]: def whoami[self]: print["I am a parent"] class Child[Parent]: def play[self]: print[" I am playing"] def whoami[self]: print["I am a child"] parent = Parent[] parent.whoami[] print[] child = Child[] child.whoami[] # Output: # I am a parent # I am a child9 sai
Ví dụ kế thừa không ghi đè phương thức
class Parent[]: def whoami[self]: print["I am a parent"] class Child[Parent]: def play[self]: print[" I am playing"] child = Child[] child.whoami[] # Output: # I am a parent
Ghi đè cơ bản
Ví dụ tiếp theo, cho thấy cách ghi đè cơ bản hoạt động. Trong ví dụ này, lớp
class Employee[]: def __init__[self, empno, ename, salary, deptno]: self.Empno = empno self.Ename = ename self.Salary = salary self.Deptno = deptno def showEmployee[self]: print["Employee # : {}\nEmployee Name : {}\nSalary : {}\nDepartment : {}".format[self.Empno, self.Ename, self.Salary, self.Deptno]] class Salesman[Employee]: def __init__[self, empno, ename, salary, deptno, comm]: self.Commission = comm super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["Salesman Profile"] super[].showEmployee[] print["Commision : ", self.Commission] class CEO[Employee]: def __init__[self, empno, ename, salary, deptno, stock]: self.Stock = stock super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["CEO Profile"] super[].showEmployee[] print["Stock Options : ", self.Stock] salesman = Salesman[200, "John Doe", 67000, "Sales", 100] salesman.showEmployee[] print[""] ceo = CEO[40, "Jennifer Smith", 300000, "Director", 1000000] ceo.showEmployee[]0 có một định nghĩa về phương thức
#Overriding class Parent[]: def whoami[self]: print["I am a parent"] class Child[Parent]: def play[self]: print[" I am playing"] def whoami[self]: print["I am a child"] parent = Parent[] parent.whoami[] print[] child = Child[] child.whoami[] # Output: # I am a parent # I am a child8 sẽ ghi đè phương thức từ lớp
class Employee[]: def __init__[self, empno, ename, salary, deptno]: self.Empno = empno self.Ename = ename self.Salary = salary self.Deptno = deptno def showEmployee[self]: print["Employee # : {}\nEmployee Name : {}\nSalary : {}\nDepartment : {}".format[self.Empno, self.Ename, self.Salary, self.Deptno]] class Salesman[Employee]: def __init__[self, empno, ename, salary, deptno, comm]: self.Commission = comm super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["Salesman Profile"] super[].showEmployee[] print["Commision : ", self.Commission] class CEO[Employee]: def __init__[self, empno, ename, salary, deptno, stock]: self.Stock = stock super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["CEO Profile"] super[].showEmployee[] print["Stock Options : ", self.Stock] salesman = Salesman[200, "John Doe", 67000, "Sales", 100] salesman.showEmployee[] print[""] ceo = CEO[40, "Jennifer Smith", 300000, "Director", 1000000] ceo.showEmployee[]5. Gọi phương thức
#Overriding class Parent[]: def whoami[self]: print["I am a parent"] class Child[Parent]: def play[self]: print[" I am playing"] def whoami[self]: print["I am a child"] parent = Parent[] parent.whoami[] print[] child = Child[] child.whoami[] # Output: # I am a parent # I am a child8 từ lớp
class Employee[]: def __init__[self, empno, ename, salary, deptno]: self.Empno = empno self.Ename = ename self.Salary = salary self.Deptno = deptno def showEmployee[self]: print["Employee # : {}\nEmployee Name : {}\nSalary : {}\nDepartment : {}".format[self.Empno, self.Ename, self.Salary, self.Deptno]] class Salesman[Employee]: def __init__[self, empno, ename, salary, deptno, comm]: self.Commission = comm super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["Salesman Profile"] super[].showEmployee[] print["Commision : ", self.Commission] class CEO[Employee]: def __init__[self, empno, ename, salary, deptno, stock]: self.Stock = stock super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["CEO Profile"] super[].showEmployee[] print["Stock Options : ", self.Stock] salesman = Salesman[200, "John Doe", 67000, "Sales", 100] salesman.showEmployee[] print[""] ceo = CEO[40, "Jennifer Smith", 300000, "Director", 1000000] ceo.showEmployee[]0 hiện hiển thị
class Employee[]: def __init__[self, empno, ename, salary, deptno]: self.Empno = empno self.Ename = ename self.Salary = salary self.Deptno = deptno def showEmployee[self]: print["Employee # : {}\nEmployee Name : {}\nSalary : {}\nDepartment : {}".format[self.Empno, self.Ename, self.Salary, self.Deptno]] class Salesman[Employee]: def __init__[self, empno, ename, salary, deptno, comm]: self.Commission = comm super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["Salesman Profile"] super[].showEmployee[] print["Commision : ", self.Commission] class CEO[Employee]: def __init__[self, empno, ename, salary, deptno, stock]: self.Stock = stock super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["CEO Profile"] super[].showEmployee[] print["Stock Options : ", self.Stock] salesman = Salesman[200, "John Doe", 67000, "Sales", 100] salesman.showEmployee[] print[""] ceo = CEO[40, "Jennifer Smith", 300000, "Director", 1000000] ceo.showEmployee[]8
Ví dụ ghi đè cơ bản
#Overriding class Parent[]: def whoami[self]: print["I am a parent"] class Child[Parent]: def play[self]: print[" I am playing"] def whoami[self]: print["I am a child"] parent = Parent[] parent.whoami[] print[] child = Child[] child.whoami[] # Output: # I am a parent # I am a child
Mở rộng một phương thức thông qua ghi đè
Ví dụ thứ ba cho thấy cách bạn có thể mở rộng một phương thức trong Lớp cơ sở bằng cách ghi đè phương thức trong Lớp con. Để làm điều đó, chúng tôi sử dụng chức năng tích hợp sẵn
class Employee[]: def __init__[self, empno, ename, salary, deptno]: self.Empno = empno self.Ename = ename self.Salary = salary self.Deptno = deptno def showEmployee[self]: print["Employee # : {}\nEmployee Name : {}\nSalary : {}\nDepartment : {}".format[self.Empno, self.Ename, self.Salary, self.Deptno]] class Salesman[Employee]: def __init__[self, empno, ename, salary, deptno, comm]: self.Commission = comm super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["Salesman Profile"] super[].showEmployee[] print["Commision : ", self.Commission] class CEO[Employee]: def __init__[self, empno, ename, salary, deptno, stock]: self.Stock = stock super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["CEO Profile"] super[].showEmployee[] print["Stock Options : ", self.Stock] salesman = Salesman[200, "John Doe", 67000, "Sales", 100] salesman.showEmployee[] print[""] ceo = CEO[40, "Jennifer Smith", 300000, "Director", 1000000] ceo.showEmployee[]9. Nó trả về một đối tượng proxy cho phép chúng ta truy cập các phương thức của lớp cơ sở. Chúng ta có thể tham chiếu đến lớp cơ sở từ lớp con mà không cần phải gọi tên lớp cơ sở một cách rõ ràng
Lớp
Salesman Profile Employee # : 200 Employee Name : John Doe Salary : 67000 Department : Sales Commision : 100 CEO Profile Employee # : 40 Employee Name : Jennifer Smith Salary : 300000 Department : Director Stock Options : 10000000 có các chi tiết sau cho nhân viên. mã số nhân viên, tên nhân viên, mức lương và, số bộ phận. Thông tin này được chuyển đến đối tượng được khởi tạo trong phương thức
Salesman Profile Employee # : 200 Employee Name : John Doe Salary : 67000 Department : Sales Commision : 100 CEO Profile Employee # : 40 Employee Name : Jennifer Smith Salary : 300000 Department : Director Stock Options : 10000001. Phương thức
Salesman Profile Employee # : 200 Employee Name : John Doe Salary : 67000 Department : Sales Commision : 100 CEO Profile Employee # : 40 Employee Name : Jennifer Smith Salary : 300000 Department : Director Stock Options : 10000002 của lớp sau đó hiển thị thông tin này được định dạng bằng các dòng mới
Lớp
Salesman Profile Employee # : 200 Employee Name : John Doe Salary : 67000 Department : Sales Commision : 100 CEO Profile Employee # : 40 Employee Name : Jennifer Smith Salary : 300000 Department : Director Stock Options : 10000003 kế thừa từ lớp
Salesman Profile Employee # : 200 Employee Name : John Doe Salary : 67000 Department : Sales Commision : 100 CEO Profile Employee # : 40 Employee Name : Jennifer Smith Salary : 300000 Department : Director Stock Options : 10000000. Theo mặc định, nó kế thừa phương thức
Salesman Profile Employee # : 200 Employee Name : John Doe Salary : 67000 Department : Sales Commision : 100 CEO Profile Employee # : 40 Employee Name : Jennifer Smith Salary : 300000 Department : Director Stock Options : 10000002 nguyên trạng từ lớp
Salesman Profile Employee # : 200 Employee Name : John Doe Salary : 67000 Department : Sales Commision : 100 CEO Profile Employee # : 40 Employee Name : Jennifer Smith Salary : 300000 Department : Director Stock Options : 10000000. Vấn đề duy nhất là chúng tôi muốn hiển thị hoa hồng mà nhân viên bán hàng nhận được như một phần của thông tin được in. Đây là nơi cần ghi đè. Chúng tôi muốn sử dụng lại phương thức
Salesman Profile Employee # : 200 Employee Name : John Doe Salary : 67000 Department : Sales Commision : 100 CEO Profile Employee # : 40 Employee Name : Jennifer Smith Salary : 300000 Department : Director Stock Options : 10000002 từ lớp
Salesman Profile Employee # : 200 Employee Name : John Doe Salary : 67000 Department : Sales Commision : 100 CEO Profile Employee # : 40 Employee Name : Jennifer Smith Salary : 300000 Department : Director Stock Options : 10000000 nhưng chúng tôi muốn mở rộng nó để thêm thông tin hoa hồng. Điều này được thực hiện bằng cách sử dụng chức năng tích hợp sẵn
class Employee[]: def __init__[self, empno, ename, salary, deptno]: self.Empno = empno self.Ename = ename self.Salary = salary self.Deptno = deptno def showEmployee[self]: print["Employee # : {}\nEmployee Name : {}\nSalary : {}\nDepartment : {}".format[self.Empno, self.Ename, self.Salary, self.Deptno]] class Salesman[Employee]: def __init__[self, empno, ename, salary, deptno, comm]: self.Commission = comm super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["Salesman Profile"] super[].showEmployee[] print["Commision : ", self.Commission] class CEO[Employee]: def __init__[self, empno, ename, salary, deptno, stock]: self.Stock = stock super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["CEO Profile"] super[].showEmployee[] print["Stock Options : ", self.Stock] salesman = Salesman[200, "John Doe", 67000, "Sales", 100] salesman.showEmployee[] print[""] ceo = CEO[40, "Jennifer Smith", 300000, "Director", 1000000] ceo.showEmployee[]9. Trong ví dụ bên dưới, bạn thấy rằng trong lớp
Salesman Profile Employee # : 200 Employee Name : John Doe Salary : 67000 Department : Sales Commision : 100 CEO Profile Employee # : 40 Employee Name : Jennifer Smith Salary : 300000 Department : Director Stock Options : 10000003,
class Employee[]: def __init__[self, empno, ename, salary, deptno]: self.Empno = empno self.Ename = ename self.Salary = salary self.Deptno = deptno def showEmployee[self]: print["Employee # : {}\nEmployee Name : {}\nSalary : {}\nDepartment : {}".format[self.Empno, self.Ename, self.Salary, self.Deptno]] class Salesman[Employee]: def __init__[self, empno, ename, salary, deptno, comm]: self.Commission = comm super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["Salesman Profile"] super[].showEmployee[] print["Commision : ", self.Commission] class CEO[Employee]: def __init__[self, empno, ename, salary, deptno, stock]: self.Stock = stock super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["CEO Profile"] super[].showEmployee[] print["Stock Options : ", self.Stock] salesman = Salesman[200, "John Doe", 67000, "Sales", 100] salesman.showEmployee[] print[""] ceo = CEO[40, "Jennifer Smith", 300000, "Director", 1000000] ceo.showEmployee[]9 được sử dụng hai lần. Phương thức
class Account[]: def __init__[self, name, number]: self.Name = name self.Number = number def display[self]: print["Account # : {}\nAccount Name : {}".format[self.Number, self.Name]] class Customer[]: def __init__[self, name, number]: self.Name = name self.Number = number def display[self]: print["Customer # : {}\nCustomer Name : {}".format[self.Number, self.Name]] class Orders[Account, Customer]: def __init__[self, acctnumber, acctname, custnumber, custname, ordnumber, ordnamename, product, qty]: self.OrdNumber = ordnumber self.Product = product self.Qty = qty self.OrdName = ordnamename self.acct = Account[acctname, acctnumber] self.cust = Customer[custname, custnumber] def display[self]: print["Order Information"] self.acct.display[] self.cust.display[] print["Order # : {}\nOrder Name : {}\nProduct : {}\nQuantiy : {}".format[self.OrdNumber, self.OrdName, self.Product, self.Qty]] acct = Account["AB Enterprise", 12345] acct.display[] print[""] cust = Customer["John Smith", 45678] cust.display[] print[""] order = Orders[12345, "AB Enterprise", 45678,"John Smith", 1, "Order 1", "Widget", 5, ] order.display[]2 sử dụng nó để gọi phương thức
class Account[]: def __init__[self, name, number]: self.Name = name self.Number = number def display[self]: print["Account # : {}\nAccount Name : {}".format[self.Number, self.Name]] class Customer[]: def __init__[self, name, number]: self.Name = name self.Number = number def display[self]: print["Customer # : {}\nCustomer Name : {}".format[self.Number, self.Name]] class Orders[Account, Customer]: def __init__[self, acctnumber, acctname, custnumber, custname, ordnumber, ordnamename, product, qty]: self.OrdNumber = ordnumber self.Product = product self.Qty = qty self.OrdName = ordnamename self.acct = Account[acctname, acctnumber] self.cust = Customer[custname, custnumber] def display[self]: print["Order Information"] self.acct.display[] self.cust.display[] print["Order # : {}\nOrder Name : {}\nProduct : {}\nQuantiy : {}".format[self.OrdNumber, self.OrdName, self.Product, self.Qty]] acct = Account["AB Enterprise", 12345] acct.display[] print[""] cust = Customer["John Smith", 45678] cust.display[] print[""] order = Orders[12345, "AB Enterprise", 45678,"John Smith", 1, "Order 1", "Widget", 5, ] order.display[]2 của lớp cơ sở Nhân viên và phương thức
Salesman Profile Employee # : 200 Employee Name : John Doe Salary : 67000 Department : Sales Commision : 100 CEO Profile Employee # : 40 Employee Name : Jennifer Smith Salary : 300000 Department : Director Stock Options : 10000002 sử dụng nó để ghi đè phương thức
Salesman Profile Employee # : 200 Employee Name : John Doe Salary : 67000 Department : Sales Commision : 100 CEO Profile Employee # : 40 Employee Name : Jennifer Smith Salary : 300000 Department : Director Stock Options : 10000002 của lớp cơ sở
Salesman Profile Employee # : 200 Employee Name : John Doe Salary : 67000 Department : Sales Commision : 100 CEO Profile Employee # : 40 Employee Name : Jennifer Smith Salary : 300000 Department : Director Stock Options : 10000000. Trong đó hiển thị thông tin nhân viên cho nhân viên bán hàng cộng hoa hồng cho nhân viên bán hàng
Lớp thứ ba có tên là
class Account[]: def __init__[self, name, number]: self.Name = name self.Number = number def display[self]: print["Account # : {}\nAccount Name : {}".format[self.Number, self.Name]] class Customer[]: def __init__[self, name, number]: self.Name = name self.Number = number def display[self]: print["Customer # : {}\nCustomer Name : {}".format[self.Number, self.Name]] class Orders[Account, Customer]: def __init__[self, acctnumber, acctname, custnumber, custname, ordnumber, ordnamename, product, qty]: self.OrdNumber = ordnumber self.Product = product self.Qty = qty self.OrdName = ordnamename self.acct = Account[acctname, acctnumber] self.cust = Customer[custname, custnumber] def display[self]: print["Order Information"] self.acct.display[] self.cust.display[] print["Order # : {}\nOrder Name : {}\nProduct : {}\nQuantiy : {}".format[self.OrdNumber, self.OrdName, self.Product, self.Qty]] acct = Account["AB Enterprise", 12345] acct.display[] print[""] cust = Customer["John Smith", 45678] cust.display[] print[""] order = Orders[12345, "AB Enterprise", 45678,"John Smith", 1, "Order 1", "Widget", 5, ] order.display[]7 sử dụng cùng logic như trước. Phương pháp
Salesman Profile Employee # : 200 Employee Name : John Doe Salary : 67000 Department : Sales Commision : 100 CEO Profile Employee # : 40 Employee Name : Jennifer Smith Salary : 300000 Department : Director Stock Options : 10000002 trong trường hợp này hiển thị thông tin nhân viên cộng với các tùy chọn cổ phiếu cho
class Account[]: def __init__[self, name, number]: self.Name = name self.Number = number def display[self]: print["Account # : {}\nAccount Name : {}".format[self.Number, self.Name]] class Customer[]: def __init__[self, name, number]: self.Name = name self.Number = number def display[self]: print["Customer # : {}\nCustomer Name : {}".format[self.Number, self.Name]] class Orders[Account, Customer]: def __init__[self, acctnumber, acctname, custnumber, custname, ordnumber, ordnamename, product, qty]: self.OrdNumber = ordnumber self.Product = product self.Qty = qty self.OrdName = ordnamename self.acct = Account[acctname, acctnumber] self.cust = Customer[custname, custnumber] def display[self]: print["Order Information"] self.acct.display[] self.cust.display[] print["Order # : {}\nOrder Name : {}\nProduct : {}\nQuantiy : {}".format[self.OrdNumber, self.OrdName, self.Product, self.Qty]] acct = Account["AB Enterprise", 12345] acct.display[] print[""] cust = Customer["John Smith", 45678] cust.display[] print[""] order = Orders[12345, "AB Enterprise", 45678,"John Smith", 1, "Order 1", "Widget", 5, ] order.display[]7
class Employee[]: def __init__[self, empno, ename, salary, deptno]: self.Empno = empno self.Ename = ename self.Salary = salary self.Deptno = deptno def showEmployee[self]: print["Employee # : {}\nEmployee Name : {}\nSalary : {}\nDepartment : {}".format[self.Empno, self.Ename, self.Salary, self.Deptno]] class Salesman[Employee]: def __init__[self, empno, ename, salary, deptno, comm]: self.Commission = comm super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["Salesman Profile"] super[].showEmployee[] print["Commision : ", self.Commission] class CEO[Employee]: def __init__[self, empno, ename, salary, deptno, stock]: self.Stock = stock super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["CEO Profile"] super[].showEmployee[] print["Stock Options : ", self.Stock] salesman = Salesman[200, "John Doe", 67000, "Sales", 100] salesman.showEmployee[] print[""] ceo = CEO[40, "Jennifer Smith", 300000, "Director", 1000000] ceo.showEmployee[]
đầu ra
Salesman Profile Employee # : 200 Employee Name : John Doe Salary : 67000 Department : Sales Commision : 100 CEO Profile Employee # : 40 Employee Name : Jennifer Smith Salary : 300000 Department : Director Stock Options : 1000000
Ghi đè nhiều kế thừa
Hiểu về đa kế thừa có những thách thức riêng. Một trong số đó là việc sử dụng
class Employee[]: def __init__[self, empno, ename, salary, deptno]: self.Empno = empno self.Ename = ename self.Salary = salary self.Deptno = deptno def showEmployee[self]: print["Employee # : {}\nEmployee Name : {}\nSalary : {}\nDepartment : {}".format[self.Empno, self.Ename, self.Salary, self.Deptno]] class Salesman[Employee]: def __init__[self, empno, ename, salary, deptno, comm]: self.Commission = comm super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["Salesman Profile"] super[].showEmployee[] print["Commision : ", self.Commission] class CEO[Employee]: def __init__[self, empno, ename, salary, deptno, stock]: self.Stock = stock super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["CEO Profile"] super[].showEmployee[] print["Stock Options : ", self.Stock] salesman = Salesman[200, "John Doe", 67000, "Sales", 100] salesman.showEmployee[] print[""] ceo = CEO[40, "Jennifer Smith", 300000, "Director", 1000000] ceo.showEmployee[]9. Đây là một liên kết đến một bài viết về vấn đề này. https. //www. trại dữ liệu. com/community/tutorials/super-multiple-inheritance-diamond-problem
Trong ví dụ bên dưới, tôi muốn chỉ ra cách ghi đè một phương thức từ một lớp con có nhiều kế thừa. Ví dụ bao gồm ba lớp.
Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order Information Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order # : 1 Order Name : Order 1 Product : Widget Quantiy : 51,
Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order Information Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order # : 1 Order Name : Order 1 Product : Widget Quantiy : 52 và
Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order Information Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order # : 1 Order Name : Order 1 Product : Widget Quantiy : 53.
- Lớp
Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order Information Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order # : 1 Order Name : Order 1 Product : Widget Quantiy : 5
1 có tên và số của nó và một phương thức hiển thị hiển thị thông tin này. - Lớp
Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order Information Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order # : 1 Order Name : Order 1 Product : Widget Quantiy : 5
2 cũng có tên và số của nó và một phương thức hiển thị hiển thị thông tin này. - Lớp
Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order Information Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order # : 1 Order Name : Order 1 Product : Widget Quantiy : 5
3 hiển thị thông tin đơn đặt hàng cho một khách hàng trong một tài khoản cụ thể. Nó kế thừa từ cả lớpAccount # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order Information Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order # : 1 Order Name : Order 1 Product : Widget Quantiy : 5
1 và Order. Phương thức hiển thị trong lớp này ghi đè lên phương thức hiển thị của các lớp cơ sở. Phương thức hiển thị in thông tin Tài khoản, thông tin Khách hàng và thông tin Đơn hàng
Đây là một ví dụ
class Account[]: def __init__[self, name, number]: self.Name = name self.Number = number def display[self]: print["Account # : {}\nAccount Name : {}".format[self.Number, self.Name]] class Customer[]: def __init__[self, name, number]: self.Name = name self.Number = number def display[self]: print["Customer # : {}\nCustomer Name : {}".format[self.Number, self.Name]] class Orders[Account, Customer]: def __init__[self, acctnumber, acctname, custnumber, custname, ordnumber, ordnamename, product, qty]: self.OrdNumber = ordnumber self.Product = product self.Qty = qty self.OrdName = ordnamename self.acct = Account[acctname, acctnumber] self.cust = Customer[custname, custnumber] def display[self]: print["Order Information"] self.acct.display[] self.cust.display[] print["Order # : {}\nOrder Name : {}\nProduct : {}\nQuantiy : {}".format[self.OrdNumber, self.OrdName, self.Product, self.Qty]] acct = Account["AB Enterprise", 12345] acct.display[] print[""] cust = Customer["John Smith", 45678] cust.display[] print[""] order = Orders[12345, "AB Enterprise", 45678,"John Smith", 1, "Order 1", "Widget", 5, ] order.display[]
đầu ra
Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order Information Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order # : 1 Order Name : Order 1 Product : Widget Quantiy : 5
Các kịch bản ghi đè khác nhau
1 – Phương thức lớp
Các phương thức của lớp đặc biệt theo nghĩa là chúng có thể được gọi trên chính một lớp hoặc bởi các thể hiện của một lớp. Chúng liên kết với một lớp, vì vậy điều này có nghĩa là đối số đầu tiên được truyền cho phương thức là một lớp chứ không phải một thể hiện
Các phương thức lớp được viết tương tự như các phương thức thể hiện thông thường. Một điểm khác biệt là việc sử dụng decorator
Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order Information Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order # : 1 Order Name : Order 1 Product : Widget Quantiy : 58 để xác định rằng phương thức này là một phương thức của lớp. Ngoài ra, theo quy ước, thay vì sử dụng self để tham chiếu thể hiện của một lớp,
Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order Information Account # : 12345 Account Name : AB Enterprise Customer # : 45678 Customer Name : John Smith Order # : 1 Order Name : Order 1 Product : Widget Quantiy : 59 đang sử dụng để tham chiếu lớp. Ví dụ
class Account[]: @classmethod def getClassVersion[cls]: print["Account class version is 1.0”]
Để biết thêm thông tin về các phương thức lớp, hãy kiểm tra trang web này
Đây là một ví dụ về vấn đề bạn sẽ gặp phải khi ghi đè một phương thức của lớp
class ParentClass: @classmethod def display[cls, arg]: print["ParentClass"] class SubClass[ParentClass]: @classmethod def display[cls, arg]: ret = ParentClass.create[cls, arg] print["Subclass"] return ret SubClass.display["test"]
đầu ra
create[] takes 2 positional arguments but 3 were given
Trong
class Account[]: @classmethod def getClassVersion[cls]: print["Account class version is 1.0”]0, lệnh gọi tới phương thức tạo
class Account[]: @classmethod def getClassVersion[cls]: print["Account class version is 1.0”]1 không phải là lệnh gọi không liên kết như cách nó xảy ra với một phương thức thể hiện thông thường. Kết quả của cuộc gọi này là TypeError vì phương thức nhận được quá nhiều đối số
Giải pháp là sử dụng
class Employee[]: def __init__[self, empno, ename, salary, deptno]: self.Empno = empno self.Ename = ename self.Salary = salary self.Deptno = deptno def showEmployee[self]: print["Employee # : {}\nEmployee Name : {}\nSalary : {}\nDepartment : {}".format[self.Empno, self.Ename, self.Salary, self.Deptno]] class Salesman[Employee]: def __init__[self, empno, ename, salary, deptno, comm]: self.Commission = comm super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["Salesman Profile"] super[].showEmployee[] print["Commision : ", self.Commission] class CEO[Employee]: def __init__[self, empno, ename, salary, deptno, stock]: self.Stock = stock super[].__init__[empno, ename, salary, deptno] def showEmployee[self]: print["CEO Profile"] super[].showEmployee[] print["Stock Options : ", self.Stock] salesman = Salesman[200, "John Doe", 67000, "Sales", 100] salesman.showEmployee[] print[""] ceo = CEO[40, "Jennifer Smith", 300000, "Director", 1000000] ceo.showEmployee[]9 để sử dụng thành công triển khai gốc
class ParentClass: @classmethod def display[cls, arg]: print["ParentClass"] class SubClass[ParentClass]: @classmethod def display[cls, arg]: ret = super[SubClass, cls].create[arg] print["Subclass"] return ret SubClass.display["test"]
đầu ra
#Overriding class Parent[]: def whoami[self]: print["I am a parent"] class Child[Parent]: def play[self]: print[" I am playing"] def whoami[self]: print["I am a child"] parent = Parent[] parent.whoami[] print[] child = Child[] child.whoami[] # Output: # I am a parent # I am a child0
2 – Phương pháp ma thuật
Phương pháp ma thuật là gì?
Các phương thức ma thuật là một tập hợp các phương thức mà Python tự động liên kết với mọi định nghĩa lớp. Các lớp của bạn có thể ghi đè các phương thức ma thuật này để triển khai các hành vi khác nhau và khiến chúng hoạt động giống như các lớp dựng sẵn của Python. Dưới đây bạn sẽ thấy các ví dụ về hai trong số những cái phổ biến nhất.
class Account[]: @classmethod def getClassVersion[cls]: print["Account class version is 1.0”]3 và
class Account[]: @classmethod def getClassVersion[cls]: print["Account class version is 1.0”]4. Sử dụng hai phương pháp này, bạn có thể triển khai cách các đối tượng của mình được hiển thị dưới dạng chuỗi, điều này sẽ rất quan trọng trong khi gỡ lỗi và trình bày thông tin cho người dùng. Ghi đè các phương thức này làm tăng tính linh hoạt và sức mạnh của Python.
Phương thức
class Account[]: @classmethod def getClassVersion[cls]: print["Account class version is 1.0”]3 của một lớp được sử dụng khi Python in một đối tượng. Phương thức kỳ diệu này được gọi bởi hàm tích hợp
class Account[]: @classmethod def getClassVersion[cls]: print["Account class version is 1.0”]6
#Overriding class Parent[]: def whoami[self]: print["I am a parent"] class Child[Parent]: def play[self]: print[" I am playing"] def whoami[self]: print["I am a child"] parent = Parent[] parent.whoami[] print[] child = Child[] child.whoami[] # Output: # I am a parent # I am a child1
đầu ra
#Overriding class Parent[]: def whoami[self]: print["I am a parent"] class Child[Parent]: def play[self]: print[" I am playing"] def whoami[self]: print["I am a child"] parent = Parent[] parent.whoami[] print[] child = Child[] child.whoami[] # Output: # I am a parent # I am a child2
đầu ra
#Overriding class Parent[]: def whoami[self]: print["I am a parent"] class Child[Parent]: def play[self]: print[" I am playing"] def whoami[self]: print["I am a child"] parent = Parent[] parent.whoami[] print[] child = Child[] child.whoami[] # Output: # I am a parent # I am a child3
Phương thức
class Account[]: @classmethod def getClassVersion[cls]: print["Account class version is 1.0”]7 của một lớp được sử dụng để hiển thị chi tiết các giá trị của một đối tượng. Phương pháp ma thuật này được gọi bằng hàm
class Account[]: @classmethod def getClassVersion[cls]: print["Account class version is 1.0”]8 tích hợp
#Overriding class Parent[]: def whoami[self]: print["I am a parent"] class Child[Parent]: def play[self]: print[" I am playing"] def whoami[self]: print["I am a child"] parent = Parent[] parent.whoami[] print[] child = Child[] child.whoami[] # Output: # I am a parent # I am a child4
đầu ra
#Overriding class Parent[]: def whoami[self]: print["I am a parent"] class Child[Parent]: def play[self]: print[" I am playing"] def whoami[self]: print["I am a child"] parent = Parent[] parent.whoami[] print[] child = Child[] child.whoami[] # Output: # I am a parent # I am a child5
Dưới đây là danh sách các phương pháp ma thuật. Bạn có thể tìm hiểu thêm về chúng tại đây [https. //www. giáo viên hướng dẫn. com/python/magic-methods-in-python] và nghĩ cách ghi đè chúng để phù hợp với nhu cầu của bạn
#Overriding class Parent[]: def whoami[self]: print["I am a parent"] class Child[Parent]: def play[self]: print[" I am playing"] def whoami[self]: print["I am a child"] parent = Parent[] parent.whoami[] print[] child = Child[] child.whoami[] # Output: # I am a parent # I am a child6
3 – Các lớp trừu tượng
Một lớp trừu tượng là một kế hoạch chi tiết mà các lớp con phải tuân theo. Nó có thể được xem như một hợp đồng giữa lớp trừu tượng và lớp con. Lớp trừu tượng cho bạn biết phải làm gì bằng cách cung cấp một phương thức trừu tượng trống và lớp con phải thực hiện nó. Theo mặc định, bạn phải ghi đè các phương thức trừu tượng được định nghĩa bởi lớp trừu tượng. Nói cách khác, chúng tôi đang cung cấp một giao diện chung cho các triển khai khác nhau của một lớp. Điều này rất hữu ích cho các dự án lớn, nơi phải triển khai một số chức năng nhất định
Dưới đây là một ví dụ về một lớp trừu tượng và các phương thức bị ghi đè trong các lớp con
#Overriding class Parent[]: def whoami[self]: print["I am a parent"] class Child[Parent]: def play[self]: print[" I am playing"] def whoami[self]: print["I am a child"] parent = Parent[] parent.whoami[] print[] child = Child[] child.whoami[] # Output: # I am a parent # I am a child7
Phần kết luận
Ghi đè là một khái niệm cơ bản được sử dụng ở nhiều nơi trong lập trình hướng đối tượng. Bạn phải hiểu nó để có thể triển khai các lớp tốt hơn và sửa đổi hành vi của chúng. Bài viết này cho bạn thấy một số ví dụ mà bạn có thể sử dụng ghi đè trong Python. Các khái niệm khác được đề cập đáng để tìm hiểu thêm là. phương pháp ma thuật và các lớp trừu tượng