Ở bài học trước chúng ta đã cùng tìm hiểu về Kế thừa trong lập trình hướng đối tượng của ngôn ngữ Python. Kế thừa 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ẽ tiếp tục bài học cùng chủ đề Kế thừa nhưng ở mức độ sâu sắc hơn, đó là Đa kế thừa và thứ tự truy xuất phương thức của các lớp cha (Method Resolution Order).

Đa kế thừa (Multiple Inheritance)

Giống như C++ thì trong Python một lớp có thể được định nghĩa từ nhiều lớp cha. Điều này được gọi là đa kế thừa.

Cú pháp:

class LopCha1:

class LopCha2:

class LopCon(LopCha1, LopCha2):

Lớp con đươc định nghĩa từ nhiều lớp cha và kế thừa đặc tính của cả hai lớp.

Các lớp cha có thể có các thuộc tính hoặc các phương thức giống nhau. Lớp con sẽ ưu tiên thừa kế thuộc tính, phương thức của lớp đứng đầu tiên trong danh sách thừa kế.

Kế thừa đa cấp (Multilevel Inheritance)

Ngoài việc có thể kế thừa từ các lớp cha, bạn còn có thể tạo lớp con mới kế thừa các lớp con trước đó. Đây gọi là kế thừa đa cấp (Multilevel Inheritance).

Với trường hợp này, các đặc tính của lớp cha và lớp con trước đó sẽ được lớp con mới kế thừa.

Cú pháp:

class LopCha:

class LopCon1(LopCha):

class LopCon2(LopCon1):

LopCon1 kế thừa LopCha, LopCon2 kế thừa LopCon1.

Thứ tự truy xuất phương thức (Method Resolution Order)

Class được bắt nguồn từ object. Trong kịch bản đa thừa kế, bất kỳ thuộc tính cần được truy xuất nào, đầu tiên sẽ được tìm kiếm trong lớp hiện tại. Nếu không tìm thấy, tìm kiếm tiếp tục vào lớp cha đầu tiên và từ trái qua phải.

Vậy thứ tự truy xuất sẽ là [LopCon, LopCha1, LopCha2, object].

Thứ tự này còn được gọi là tuyến tính hóa của LopCon và tập hợp các quy tắc được sử dụng để tìm thứ tự này được gọi là Thứ tự truy xuất phương thức (MRO).

Nói một cách dễ hiểu, MRO dùng để hiển thị danh sách/tuple các class cha của một class nào đó.

MRO được sử dụng theo hai cách:

  • __mro__: trả về một tuple
  • mro(): trả về một danh sách.
>>> LopCon.__mro__
(<class '__main__.LopCon'>,
 <class '__main__.LopCha1'>,
 <class '__main__.LopCha2'>,
 <class 'object'>)

>>> LopCon.mro()
[<class '__main__.LopCon>,
 <class '__main__.LopCha1'>,
 <class '__main__.LopCha2'>,
 <class 'object'>]

Dưới đây là một ví dụ thừa kế phức tạp và hiển thị trực quan của nó cùng với MRO.

class X: pass
class Y: pass
class Z: pass

class A(X,Y): pass
class B(Y,Z): pass

class M(B,A,Z): pass

# Output:
# [<class '__main__.M'>, <class '__main__.B'>,
# <class '__main__.A'>, <class '__main__.X'>,
# <class '__main__.Y'>, <class '__main__.Z'>,
# <class 'object'>]


  1. Good day! This post couldn’t be written any better!
    Reading through this post reminds me of my old room mate!
    He always kept talking about this. I will forward this post to him.
    Pretty sure he will have a good read. Thanks for

  2. Hey very cool site!! Man .. Excellent .. Wonderful ..
    I will bookmark your site and take the feeds additionally?
    I’m satisfied to seek out a lot of useful information right here within the submit, we need develop
    extra techniques in this regard, thanks for sharing.
    . . . . .

  3. Amazing blog! Is your theme custom made or did you download it from somewhere?
    A design like yours with a few simple adjustements would really make my blog shine.
    Please let me know where you got your theme. Many thanks

  4. Good day! I know this is kinda off topic but I’d figured I’d ask.
    Would you be interested in exchanging links or maybe guest writing a
    blog post or vice-versa? My website covers a lot
    of the same subjects as yours and I feel we could greatly benefit from each other.
    If you happen to be interested feel free to shoot me an e-mail.

    I look forward to hearing from you! Superb blog by the way!

  5. I like the helpful information you provide in your articles.
    I’ll bookmark your weblog and check again here frequently.
    I’m quite sure I’ll learn many new stuff right here! Best of luck
    for the next!

  6. I’ve been surfing online more than three hours today,
    yet I never found any interesting article like yours.
    It is pretty worth enough for me. In my opinion, if all web owners and bloggers
    made good content as you did, the internet will be much more
    useful than ever before.

  7. It’s truly a great and useful piece of info.
    I’m glad that you simply shared this helpful info with us.
    Please stay us informed like this. Thank you for sharing.

  8. We stumbled over here different web page and thought
    I should check things out. I like what I see so i am just following you.
    Look forward to looking at your web page for a second time.

  9. We’re a group of volunteers and opening a new scheme
    in our community. Your web site provided us with
    valuable info to work on. You’ve done a formidable job and
    our whole community will be grateful to you.

  10. Hmm it appears like your blog ate my first comment (it was extremely long) so I guess I’ll just sum it up what I wrote and say, I’m thoroughly enjoying your blog.
    I too am an aspiring blog writer but I’m still new to the whole
    thing. Do you have any recommendations for novice blog
    writers? I’d really appreciate it.

  11. Thanks for a marvelous posting! I truly enjoyed reading it, you can be a great author.
    I will make sure to bookmark your blog and may come back down the road.
    I want to encourage continue your great writing,
    have a nice morning!

  12. Great post but I was wondering if you could write a litte more on this subject?
    I’d be very thankful if you could elaborate a little bit
    more. Bless you!

  13. I simply could not depart your web site before suggesting that I actually enjoyed the standard info an individual supply in your visitors? Is gonna be again continuously in order to inspect new posts

  14. Aw, this was an extremely good post. Taking the time and actual effort to create a superb articleÖ but what can I sayÖ I put things off a whole lot and don’t manage to get anything done.

  15. You are so interesting! I don’t suppose I have read through something like that before. So great to find another person with some genuine thoughts on this subject. Really.. thank you for starting this up. This web site is something that is required on the web, someone with a bit of originality!

  16. When I originally left a comment I appear to have clicked on the -Notify me when new comments are added- checkbox and now each time a comment is added I receive 4 emails with the same comment. Perhaps there is an easy method you can remove me from that service? Thanks!

  17. An impressive share! I’ve just forwarded this onto a co-worker who was conducting a little homework on this. And he in fact ordered me dinner due to the fact that I found it for him… lol. So allow me to reword this…. Thank YOU for the meal!! But yeah, thanx for spending time to discuss this topic here on your site.

  18. It as unbreakable to attain knowledgeable nation proceeding this topic however you sound in the vein of you know what you are talking about! Thanks

  19. Terrific work! This is the type of information that should be shared around the web. Shame on Google for not positioning this post higher! Come on over and visit my web site. Thanks =)

  20. themselves, particularly contemplating the truth that you could possibly have carried out it for those who ever decided. The pointers as well served to provide an incredible solution to

  21. Your style is really unique compared to other people I ave read stuff from. Many thanks for posting when you have the opportunity, Guess I will just book mark this blog.

  22. Es muy frecuente que este mal aparezca por derivación de problemas psicológicos, como los mencionados de vivir en una sociedad exigente como la nuestra, en la que la virilidad se encuentra socialmente relacionada con el éxito profesional y social, y en la que se exige más de lo que se debe en el plano sexual, condicionado por lo que creemos que es lo correcto, etc.

  23. It as genuinely very complex in this busy life to listen news on TV, thus I only use internet for that purpose, and get the most up-to-date news.

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

  25. Normally I don at read article on blogs, however I would like to say that this write-up very compelled me to check out and do so! Your writing style has been amazed me. Thanks, quite great article.

  26. I think that may be an interesting element, it made me assume a bit. Thanks for sparking my considering cap. On occasion I get so much in a rut that I simply really feel like a record.

  27. I think other site proprietors should take this website as an model, very clean and excellent user genial style and design, let alone the content. You are an expert in this topic!

  28. Danke für Die Schönen Aufschreiben. Ich sind schon recherchieren dieses Thema für irgendwann . Die Artikel und Besonderheiten Sie zeigen, ich war nicht bewusst Über. Ich wird verfolgend Ihre Blog jetzt und mit etwas Glück Sie werden mehr Ansichten und Einsichten.

  29. Is not it amazing whenever you discover a fantastic article? My personal web browsings seem full.. thanks. Respect the admission you furnished.. Extremely valuable perception, thanks for blogging..

  30. Sounds like anything plenty of forty somethings and beyond ought to study. The feelings of neglect is there in a lot of levels every time a single ends the mountain.

  31. Magnificent beat ! I would like to apprentice while you amend your website, how can i subscribe for a blog site? The account helped me a acceptable deal. I had been tiny bit acquainted of this your broadcast offered bright clear concept

  32. Thank you a lot for sharing this with all people you actually recognise what you are speaking about! Bookmarked. Kindly also discuss with my site =). We can have a link trade agreement between us!

  33. This very blog is really awesome and also amusing. I have found a lot of interesting things out of this amazing blog. I ad love to go back again soon. Cheers!

  34. Pretty nice post. I just stumbled upon your blog and wanted to say that I have really enjoyed browsing your blog posts. In any case I will be subscribing to your feed and I hope you write again soon!

  35. Wonderful blog! I found it while searching on Yahoo News. Do you have any tips on how to get listed in Yahoo News? I ave been trying for a while but I never seem to get there! Appreciate it

  36. Hi, just required you to know I he added your site to my Google bookmarks due to your layout. But seriously, I believe your internet site has 1 in the freshest theme I??ve came across. It extremely helps make reading your blog significantly easier.

  37. Hi, I think your site might be having browser compatibility issues. When I look at your website in Safari, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, fantastic blog!

  38. Thanks a bunch for sharing this with all of us you actually know what you’re talking about! Bookmarked. Kindly also visit my site =). We could have a link exchange agreement between us!

  39. Hi, just required you to know I he added your site to my Google bookmarks due to your layout. But seriously, I believe your internet site has 1 in the freshest theme I??ve came across. It extremely helps make reading your blog significantly easier.

  40. Those are yours alright! . We at least need to get these people stealing images to start blogging! They probably just did a image search and grabbed them. They look good though!

  41. Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!

  42. Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!

  43. Today, I went to the beach front with my children. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is totally off topic but I had to tell someone!

  44. Attractive element of content. I simply stumbled upon your site and in accession capital to assert that I get actually loved account your blog posts. Anyway I will be subscribing to your feeds and even I achievement you access constantly quickly.

  45. I love your blog.. very nice colors & theme. Did you create this website yourself? Plz reply back as I’m looking to create my own blog and would like to know wheere u got this from. thanks

  46. Hi there! This post couldn’t be written any better! Reading through this post reminds me of my previous room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thank you for sharing!

  47. Thanx for the effort, keep up the good work Great work, I am going to start a small Blog Engine course work using your site I hope you enjoy blogging with the popular BlogEngine.net.Thethoughts you express are really awesome. Hope you will right some more posts.

  48. I would like to thnkx for the efforts you have put in writing this blog. I am hoping the same high-grade blog post from you in the upcoming as well. In fact your creative writing abilities has inspired me to get my own blog now. Really the blogging is spreading its wings quickly. Your write up is a good example of it.

  49. hey there and thank you on your information – I have definitely picked up anything new from right here. I did however experience some technical points the usage of this website, since I experienced to reload the web site many times prior to I may just get it to load correctly. I were wondering in case your web host is OK? Not that I’m complaining, but slow loading circumstances times will very frequently have an effect on your placement in google and can harm your quality rating if ads and ***********|advertising|advertising|advertising and *********** with Adwords. Anyway I am adding this RSS to my e-mail and can look out for much more of your respective exciting content. Ensure that you update this once more soon..


Please enter your comment!
Please enter your name here