Python design mode-Template method mode

Source: Internet
Author: User

1. Template Method mode

To do a problem:

Requirement: There are two students to answer questions and write their own answers

#Encoding=utf-8__author__='[email protected]'classStudenta ():defAnswer1 (self):Print 'topic One: XXXXXX'        Print 'my answer is: B'    defAnswer2 (self):Print 'topic One: XXXXXX'        Print 'my answer is: B'classstudentb ():defAnswer1 (self):Print 'topic One: XXXXXX'        Print 'my answer is: C'    defAnswer2 (self):Print 'topic One: XXXXXX'        Print 'my answer is: D'if __name__=='__main__': Student_a=Studenta () student_a.answer1 () Student_a.answer2 () student_b=studentb () student_b.answer1 () Student_b.answer2 ( )

This writing is sure to repeat too many things, such as writing a topic, such as "My answer is" and so on, if we need to create a lot of studentx class, in case one day need to change the topic, we have to change a lot of things,

So the purpose of the template method mode is that all the repetition of things, that need to write more than two times in a template (can be a parent class, can also be a function)

The implementation of the template method:

#Encoding=utf-8__author__='[email protected]'classStudent ():defAnswer1 (self):Print 'topic One: XXXXXX'        Print 'My answer is:%s'%Self.get_answer1 ()defGet_answer1 (self):return 'A'    defAnswer2 (self):Print 'topic One: XXXXXX'        Print 'My answer is:%s'%Self.get_answer2 ()defGet_answer2 (self):return 'A'classStudenta ():defGet_answer1 (self):return 'B'    defGet_answer2 (self):return 'B'classstudentb ():defAnswer1 (self):return 'C'    defAnswer2 (self):return 'D'if __name__=='__main__': Student_a=Studenta () student_a.answer1 () Student_a.answer2 () student_b=studentb () student_b.answer1 () Student_b.answer2 ( )

One technique used here is that you can define a common method in the parent class, and then the subclass overrides this method to implement the differentiation between subclasses.

Python design mode-Template method mode

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.