Kế thừa trong lập trình hướng đối tượng cho phép chúng ta khai báo lớp mới sử dụng lại các hàm và thuộc tính của lớp cha cùng các chức năng mở rộng thêm. Trong bài viết này,Tin học của em sẽ cùng bạn học cách sử dụng tính kế thừa trong Python.

Kế thừa là gì?

Kế thừa (Inheritance) cho phép một lớp (class) có thể kế thừa các thuộc tính và phương thức từ các lớp khác đã được định nghĩa. Lớp đã có gọi là lớp cha (base class hoặc parent class), lớp mới phát sinh gọi là lớp con (child class hoặc derived class). Lớp con kế thừa tất cả thành phần của lớp cha, có thể mở rộng các thành phần kế thừa và bổ sung thêm các thành phần mới.

Cú pháp của kế thừa

class BaseClass:
     Body of base class

class DerivedClass(BaseClass):
     Body of derived class

Để rõ hơn về việc sử dụng kế thừa, chúng ta hãy lấy một ví dụ.

Đa giác là một hình khép kín có 3 cạnh trở lên. Chúng ta có một lớp gọi là DaGiac được định nghĩa như sau.

class DaGiac:

     def __init__(self, socanh):
        self.n = socanh
        self.canh = [0 for i in range(socanh)]

     def nhapcanh(self):
        self.canh = [float(input("Bạn hãy nhập giá trị cạnh "+str(i+1)+" : ")) for i in range(self.n)]

     def hienthicanh(self):
        for i in range(self.n):
        print("Giá trị cạnh",i+1,"là",self.canh[i])

Class DaGiac có thuộc tính n để định nghĩa số cạnh và canh để lưu giá trị mỗi cạnh. Hàm nhapcanh() lấy độ lớn các cạnh và hienthicanh() sẽ hiện thị danh sách các cạnh của đa giác.

Hình tam giác là đa giác có ba cạnh, nên ta sẽ tạo một lớp TamGiac kế thừa từ DaGiac.Class mới này sẽ thừa kế tất cả các thuộc tính sẵn có trong lớp cha nên bạn sẽ không cần khai báo lại (khả năng sử dụng lại code). TamGiac này được khai báo như sau:

class TamGiac(DaGiac):

     def __init__(self):
        DaGiac.__init__(self,3)

     def dientich(self):
        a, b, c = self.canh
        # Tính nửa chu vi
        s = (a + b + c) / 2
        area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
        print('Diện tích của hình tam giác là %0.2f' %area)

Lớp TamGiac không chỉ kế thừa mà còn định nghĩa thêm một hàm mới là hàm dientich.

>>> t = TamGiac()
>>> t.nhapcanh()
Bn hãy nhp giá tr cnh 1 : 3
Bn hãy nhp giá tr cnh 2 : 5
Bn hãy nhp giá tr cnh 3 : 4

>>> t.hienthicanh()
Giá tr cnh 1 là 3.0
Giá tr cnh 2 là 5.0
Giá tr cnh 3 là 4.0

>>> t.dientich()
Din tích ca hình tam giác là 6.00

Ta có thể thấy, các hàm nhapcanh(), hienthicanh() đều không có trong class TamGiac, nhưng chúng ta vẫn sử dụng được chúng

Overriding (Ghi đè) trong Python

Python cho phép ghi đè lên các phương thức của lớp cha. Bạn có thể thực hiện việc ghi đè phương thức của lớp cha nếu muốn có tính năng khác biệt hoặc đặc biệt trong lớp con.

Trong ví dụ trên ta thấy class TamGiac sử dụng lại hàm __init__() từ class DaGiac, nếu bạn muốn override (ghi đè) lại định nghĩa của hàm __init__() trong class cha, ta dùng hàm super().

super () .__ init __ (3) tương đương với DaGiac.__ init __ (self, 3)

Ngoài ra Python có hai hàm isinstance() và issubclass() được dùng để kiểm tra mối quan hệ của hai lớp và instance.

Hàm issubclass(classA, classB) trả về True nếu class A là lớp con của class B.

>>> issubclass(DaGiac,TamGiac)
False

>>> issubclass(TamGiac,DaGiac)
True

>>> issubclass(bool,int)
True

Hàm isinstance(obj, Class) trả về True nếu obj là một instance của lớp Class hoặc là một instance của lớp con của Class.

>>> isinstance(t,TamGiac)
True

>>> isinstance(t,DaGiac)
True

>>> isinstance(t,int)
False

>>> isinstance(t,object)
True

216 BÌNH LUẬN

  1. always i used to read smaller content which as well
    clear their motive, and that is also happening with this article which I am reading at this
    place.

  2. I have read a few just right stuff here. Definitely value bookmarking for revisiting.
    I surprise how so much effort you set to make this kind of wonderful
    informative site.

  3. Your style is very unique in comparison to other folks I ave read stuff from. Many thanks for posting when you have the opportunity, Guess I all just book mark this page.

  4. Hello there! I simply wish to give you a big thumbs up for the excellent information you have got here on this post.

    I’ll be coming back to your blog for more soon.

  5. You’ve made some really good points there. I looked on the web to learn more about
    the issue and found most people will go along with your views on this
    web site.

  6. Greate pieces. Keep posting such kind of info on your page.
    Im really impressed by your blog.
    Hello there, You have performed a great job. I will certainly digg it and in my
    opinion suggest to my friends. I’m sure they will be benefited
    from this web site.

  7. I’m impressed, I must say. Rarely do I come across a blog
    that’s both equally educative and amusing, and let me tell you, you have hit the
    nail on the head. The issue is something that not enough folks are speaking intelligently about.
    I am very happy I came across this in my search for something regarding this.

  8. Thanks a bunch for sharing this with all of us you actually realize what you are talking approximately!
    Bookmarked. Kindly also discuss with my web site =).
    We will have a link exchange agreement among us

  9. Usually I don at learn post on blogs, however I would like to say that this write-up very forced me to take a look at and do it! Your writing style has been amazed me. Thank you, quite nice article.

  10. Wow, marvelous blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is excellent, let alone the content!. Thanks For Your article about sex.

  11. Wow, amazing blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is wonderful, as well as the content!. Thanks For Your article about sex.

  12. Thank you, I ave just been searching for info about this topic for ages and yours is the greatest I ave discovered so far. But, what about the conclusion? Are you sure about the source?

  13. You could definitely see your enthusiasm in the work you write. The world hopes for more passionate writers like you who are not afraid to mention how they believe. At all times follow your heart.

  14. Hi there! Quick question that’s totally off topic. Do you know how to make your site
    mobile friendly? My site looks weird when viewing from my iphone.
    I’m trying to find a theme or plugin that
    might be able to fix this issue. If you have any recommendations, please share.
    Thank you!

  15. Hey would you mind letting me know which webhost you’re utilizing?
    I’ve loaded your blog in 3 completely different browsers and I must say this blog loads a lot quicker then most.
    Can you suggest a good hosting provider at a honest price?

    Thanks a lot, I appreciate it!

  16. I do not even know how I ended up here, but I thought this post
    was great. I do not know who you are but definitely you’re going to
    a famous blogger if you are not already
    😉 Cheers!

  17. I’m impressed, I must say. Seldom do I encounter a
    blog that’s both educative and entertaining, and without a doubt, you have hit the
    nail on the head. The issue is something that too few folks are
    speaking intelligently about. Now i’m very happy I found this
    in my search for something relating to this.

  18. Having read this I believed it was rather informative. I appreciate you
    finding the time and energy to put this short article together.
    I once again find myself spending a lot of time both reading and commenting.

    But so what, it was still worth it!

  19. Heya i’m for the primary time here. I found this board and I find It truly
    useful & it helped me out much. I am hoping to give something again and
    aid others such as you aided me.

  20. Thank you for some other magnificent post. Where else may anybody get that type of info in such an ideal method of writing? I have a presentation subsequent week, and I am on the search for such info.

  21. This is very interesting, You are a very skilled blogger. I ave joined your rss feed and look forward to seeking more of your great post. Also, I ave shared your site in my social networks!

  22. Your style is so unique compared to other people I ave read stuff from. I appreciate you for posting when you have the opportunity, Guess I will just book mark this page.

  23. Wow! This could be one particular of the most helpful blogs We ave ever arrive across on this subject. Actually Great. I am also a specialist in this topic so I can understand your hard work.

  24. magnificent submit, very informative. I wonder why the opposite experts of this sector do not realize this. You should continue your writing. I am confident, you ave a great readers a base already!

  25. You ave made some really good points there. I checked on the web for more info about the issue and found most people will go along with your views on this web site.

  26. This is very interesting, You are a very skilled blogger. I have joined your rss feed and look forward to seeking more of your wonderful post. Also, I have shared your site in my social networks!

  27. Thanks for every other excellent article. The place else may just anybody get that type of info in such an ideal means of writing? I have a presentation next week, and I am at the look for such info.

  28. Pretty section of content. I just stumbled upon your site and in accession capital
    to assert that I get actually enjoyed account your blog posts.
    Any way I’ll be subscribing to your feeds and even I achievement you access consistently
    quickly.

THOÁT KHỎI BÌNH LUẬN

Please enter your comment!
Please enter your name here