[Python] Mixin literacy class

Source: Internet
Author: User
Tags pears

Mixin literacy classLai Yong Hao (http://blog.csdn.net/lanphaday) Statement: This article is suitable for junior and intermediate Python programmers to read, in addition to the wording of this article may cause reader discomfort, please PG. IntroductionWell, why do you want to talk about Mixin? Because of the appearance of a Mixin, like many people in the C ++ community talking about templates, many in the python community will talk about Mixin (which will happen in the future ), so I came to join in. Well, why Mixin? This is basically what I want to talk about in this article. Therefore, I will use most of the content in this article to answer your questions that are extremely deep. Now, let's get started ~ When I was a child, I opened a department store. Of course, I also had fruit and vegetables. When I was a child, it was always very interesting and meaningful. So let's start with a fruit shop today ~ I remember, when many people used to buy fruit, they would ask my mom a question, that is, the price ~ But there are two other questions that I often ask: what kind of fruit should I buy and what kind of fruit can be used to deliver? Well, most young people do not understand these etiquette. Fruit delivery is also a sign-off. For example, pears and bananas generally do not need to be sent, because they mean parting and anxiety. Apple and oranges are very popular because they mean peace and good luck ~ Start with thisSo, what does this have to do with python? Of course. What else do I do with so much skin? Now, Ling Lingqi has received a task asking him to develop a set of software for a fruit chain store. Obviously, Wu, who is not concerned with the national economy and livelihood, cannot undertake this arduous task, he finds you. Through research, the customer found two facts: first, the current young people do not know what fruits should be bought and what fruits can be used to send people; second, 100% of fruit chain stores are young people, they don't understand either. Therefore, the customer decides that such a function must be provided in the software-to check whether a fruit is suitable for sending. Initially, you may design it like this: Class fruit (object): Pass uses the fruit class as the base class for all fruits. Well, this is wise. Code removes unnecessary code, such as price and origin. Now you are planning to implement the most popular apple: Class Apple (fruit): def is_gift_fruit (Self): Return true. I will remove some codes that do not need to be concerned, we will not remind you of this in the following lines. Apple is a fruit. Therefore, the above implementation conforms to the OO principle. Next let's implement pear: Class pear (fruit): def is_gift_fruit (Self): Return false to solve the problem. If the fruit chain stores only apple and pears. Unfortunately, there are a lot of demands. You need oranges and bananas. You have written these lines of code: Class orange (fruit): def is_gift_fruit (Self): Return trueclass banana (fruit): def is_gift_fruit (Self): Return false, bad taste of code! Similar to Apple and orange, apart from different class names, the code is almost completely duplicated; the same is true for pear and banana. In the further layer, these four classes are similar, so we need to refactor the existing code to improve their design. Improve existing codeAfter reading the code, you can find that there are only two types of fruits: one can be used as a gift, and the other is not. So we hope we can design it like this: fruit // giftfruit notgiftfruit ///Apple orange pear banana. Well, two intermediate classes are added, which looks good: Class giftfruit (fruit ): def evaluate (Self): Return trueclass notgiftfruit (fruit): def evaluate (Self): Return falseclass Apple (giftfruit): passclass orange (giftfruit): passclass pear (break ): passclass banana (notgiftfruit): Pass is good. It looks good. The code is much simplified and the task is completed ~ New troublesNext, let's complete another function: provide consultation on fruit consumption methods. Don't laugh at this demand. This is a real market demand. For example, a considerable number of friends who have lived in the north for a lifetime have never eaten longan, Lychee, and bananas. Although there are abundant fruits in the south, there are also many people who do not know about bamboo and other foreign fruits. Our fruit chain stores have simple business and there are only two ways to eat fruits: one is peeled, such as oranges and bananas, and the other is peeled, such as apples and pears. Let's modify the original design: fruit // giftfruit notgiftfruit // pareg... huskg... parenot... husknot... /// Apple orange pear banana: Class paregiftfruit (giftfruit): def eat_method (Self): Return 'pare' class hustgiftfruit (giftfruit ): def eat_method (Self): Return 'husk' class evaluate (notgiftfruit): def eat_method (Self): Return 'pare' class husknotgiftfruit (notgiftfruit): def eat_method (SEL F): Return 'husk'. Why are these four classes so similar? Khan .... The implementation of four aopb fruits should be changed to: Class Apple (paregiftfruit): passclass orange (huskgiftfruit): passclass pear (fruit): passclass banana (fruit ): I can't bear it anymore. This design not only introduces repetitive code that is hard to eliminate, but also modifies the implementation of the four classes aopb. The scalability of this design is not good, if you want to provide other characteristics of fruit in the future, such as imported fruit or domestic fruit. Oh, my God, this is enough! With this feature, I want to implement eight class localparegiftfruit and localhuskgiftfruit (three power of 2. The fruit has many characteristics. A Random calculation may contain more than 16 types, 65536 categories? Let me die ~ The class name that is up to 16 words alone breaks down! Now, you should all realize that this implementation method is actually a kind of zookeeper design. So how should we design it? Pythonic SolutionIt's time for Mixin to come out! Let's take a look at the implementation of Mixin: Class fruit (object): passclass giftmixin (object): def is_gift_fruit (Self): Return trueclass notgiftmixin (object): def is_gift_fruit ): return falseclass paremixin (object): def eat_method (Self): Return 'pare' class huskmixin (object): def eat_method (Self): Return 'husk' class Apple (giftmixin, paremixin, fruit): passclass orange (giftmixin, huskmixin, fruit): passclass pear (notgiftmixin, Paremixin, fruit): passclass banana (notgiftmixin, huskmixin, fruit): pass encoding is complete! This is Mixin, which is so simple that I can no longer say anything, because I think the above Code has completely expressed what I want to express. The advantage of Mixin is that you can add any number of mixins to the main class (such as fruit) to achieve polymorphism. For example, the fruit mentioned earlier has two characteristics: imported and made, which is quite easy to implement now: class nativemixin (object): def locality (Self): Return 'native 'class foreignmixin (object): def locality (Self): Return 'foreign' class Apple (foreignmixin, giftmixin, paremixin, fruit): pass # imported Red Fuji class orange (batch, giftmixin, huskmixin, fruit): passclass pear (batch, notgiftmixin, paremixin, fruit): passclass banana N, notgiftmixin, huskmixin, and fruit): Pass is much simpler, and only two classes are added. The aopb implementation only adds a base class (adding is always better than modifying ). Using Mixin, we can also add numerous features without making too many changes to the existing code. In additionAt this time, you may say: the fruit chain store software is just a project you have fabricated. What is the practical use of Mixin? Of course! In fact, Mixin is not a high-level Python technique. Many open-source projects have used this technique. It is typical, such as a python project! Simpleserver. in py, Mixin is applied to implement two TCP/UDP Service Models Based on processes and threads. It can also be seen in tkinter and other Python modules, if you pay attention to it. Specifically, I am still quite dissatisfied with the implementation of the fruit chain stores implemented by Mixin, but if we want to be object-oriented enough, we can basically only accept such a solution. If one day you cannot stand adding a feature, you must write n (n> = 2) Mixin, then, you must add a base class to the existing aopb code (think about it, there are more than four types of fruit sold by the fruit store, and you will get bigger). Then, consider dropping oo! ThanksIn the process of writing this article, Shen Yu (http://eishn.blog.163.com) to me a lot of help, I would like to thank you.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.