类与包装

By admin in 必赢网址是多少 on 2019年4月12日

1 Why Class

(那篇文章是一篇新手级的小说,请权威绕道)
初期人们编制程序的时候都以用经过在编制程序。不过随着使用的中肯,人们开始使用类。大约的前进进度是如此:

过程—> 过程+函数 —> 类 —> 类&子类……

咱俩作为多个初专家的时候,往往不精晓为何要用类,为何不间接用经过就好了。Well,
简短的程序是能够用经过+函数,不过1旦要提到到众多调用的意况,依旧要有Class,让全数程序都得以看起来很爽快。

2 Class is an abstract of things

上边举3个例证:
Al在它的书里头第十章[https://automatetheboringstuff.com/chapter8/\]
讲了八个project(Project: Generating Random Quiz
Files),就是讲的贰个有一个地理教员,他保管了2个3二十人的班级,准备给他们出一套试题,考考United States的414个州和各种州的省会;由于有成千成万童鞋喜欢抄袭,所以那些老师就准备每一种学生准备1份(花旗国教师好敬业啊,遥想读书当年,大家的园丁最多就提过AB卷),不过壹旦人工来准备太难为了,所以老师决定自动化。

要消除的思绪很简短,正是通过多少个循环,将答案shuffle开正是,那里写1段伪代码讲讲大约思路:

for 童鞋 = 1 to 童鞋总数(35):
    随机打乱50题

for 每一题 = 1 to 题目总数(50):

             生成正确的答案+错误的答案

             打印问题到试卷文件中

             打印答案到答案文件中

切实思路请看Al的帖子[https://automatetheboringstuff.com/chapter8/\]
,搜索Generating Random Quiz Files。

新的难题

那便是说以往题材来了,假设是有一个神州的地理教员是您的爱人,准备跟国际接轨,考中华夏族民共和国的3五个省的省会,而班上有陆15位同学,你也准备每人准备一套试卷,要怎么准备呢?

有七个简便的点子正是改参数,然则,那样的难点是,大概还要程序也会来得很ad-hoc。若是又是另一个国家的又如何是好。假使这几个地理教员下次再找到你,让你支持给班上57人同学准备有4八道题的考卷呢?

3 Class Solution

因此那边建议类的法子。听过类的童鞋都晓得类有『封装,继承,多态』八个属性。我们那边会用到封装。
此间是将Al的章程改为Class之后的结果:

# -- coding: utf-8 --# RandomQuizGenerator.pyimport randomcapitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',            'Arkansas': 'Little Rock', 'California': 'Sacramento',            'Colorado': 'Denver', 'Connecticut': 'Hartford', 'Delaware': 'Dover',            'Florida': 'Tallahassee', 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu',            'Idaho': 'Boise', 'Illinois': 'Springfield', 'Indiana': 'Indianapolis',            'Iowa': 'Des Moines', 'Kansas': 'Topeka', 'Kentucky': 'Frankfort',            'Louisiana': 'Baton Rouge', 'Maine': 'Augusta', 'Maryland': 'Annapolis',            'Massachusetts': 'Boston', 'Michigan': 'Lansing', 'Minnesota': 'Saint Paul',            'Mississippi': 'Jackson', 'Missouri': 'Jefferson City', 'Montana':                'Helena', 'Nebraska': 'Lincoln', 'Nevada': 'Carson City', 'New Hampshire':                'Concord', 'New Jersey': 'Trenton', 'New Mexico': 'Santa Fe', 'New York':                'Albany', 'North Carolina': 'Raleigh', 'North Dakota': 'Bismarck', 'Ohio':                'Columbus', 'Oklahoma': 'Oklahoma City', 'Oregon': 'Salem', 'Pennsylvania':                'Harrisburg', 'Rhode Island': 'Providence', 'South Carolina': 'Columbia',            'South Dakota': 'Pierre', 'Tennessee': 'Nashville', 'Texas': 'Austin',            'Utah': 'Salt Lake City', 'Vermont': 'Montpelier', 'Virginia': 'Richmond',            'Washington': 'Olympia', 'West Virginia': 'Charleston',            'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'}NUM_OF_STUDENTS = 35NUM_OF_QUESTIONS = 50class RandomQuizGenerator():    def __init__(self, capitals, number_of_students, number_of_questions):        self.capitals = capitals        self.number_of_students = number_of_students        self.number_of_questions = number_of_questions        self.quiz_file = None        self.quiz_answer_file = None    def run(self):        # TODO create a loop of number_of_students quizzes        for quiz_num in range(self.number_of_students):            # Create the quiz and answer key files.            self.init_quiz_file(quiz_num)            # Generate random questions' order for each quiz.            unique_states_list = list(self.capitals.keys())            random.shuffle(unique_states_list)            # loop through all 50 States, making a question for each.            self.generate_one_quiz(unique_states_list)            # Close the quiz_file and the quiz_answer_file            self.close_quiz_file()    def init_quiz_file(self, quiz_num):        self.quiz_file = open('capitalsQuiz%s.txt' % (quiz_num + 1), 'w')        self.quiz_answer_file = open('capitalsQuiz_Answers%s.txt' % (quiz_num + 1), 'w')        # Write out the header for the quiz.        self.quiz_file.write('Name:\n\nDate:\n\nPeriod:\n\n')        self.quiz_file.write((' ' * 20) + 'States Capitals Quiz (Form %s)'                             % (quiz_num + 1))        self.quiz_file.write('\n\n')    def close_quiz_file(self):        self.quiz_file.close()        self.quiz_answer_file.close()    def generate_one_quiz(self, unique_states_list):        for question_num in range(self.number_of_questions):            # Generate wrong answers            question_state = unique_states_list[question_num]            correct_answer = self.capitals[question_state]            wrong_answers = list(self.capitals.values())            del wrong_answers[wrong_answers.index(correct_answer)]            wrong_answers = random.sample(wrong_answers, 3)            # Get the right answer and mingle with the wrong one            answer_options = wrong_answers + [correct_answer]            random.shuffle(answer_options)            # Write the answer to the self.quiz_file            self.quiz_file.write('%s. What is the capital of %s?\n'                                 % (question_num + 1, question_state.encode('utf-8')))            for i in range(4):                self.quiz_file.write(' %s. %s\n' % ('ABCD'[i], answer_options[i].encode('utf-8')))            self.quiz_file.write('\n')            # Write the answer to the self.quiz_answer_file            self.quiz_answer_file.write('%s. %s\n' % (question_num + 1,                                                      'ABCD'[answer_options.index(correct_answer)]))    def change_save_file_name(self, quiz_save_name, answer_save_name):        # TODO The teacher can change the name of the save file.        passdef main():    random_quiz_generator = RandomQuizGenerator(capitals, NUM_OF_STUDENTS, NUM_OF_QUESTIONS)    random_quiz_generator.run()    passif __name__ == '__main__':    main()

¥¥¥¥¥¥¥¥¥¥¥我是文本的分界线¥¥¥¥¥¥¥¥¥¥

必赢网址是多少,封装

您也许会说,那一个望着比原来更复杂啊,但是,即便这些是拿给地理教员,他并不须要懂上边那一段,他只必要看懂下边那段代码正是了:

# -- coding: utf-8 --
# china_provincial_capital.py
import RandomQuizGenerator

capitals = {u'北京': u'北京', u'上海': u'上海', u'天津': u'天津', u'重庆':u'重庆', u'新疆': u'乌鲁木齐',
            u'黑龙江': u'哈尔滨', u'吉林': u'长春', u'辽宁': u'沈阳', u'内蒙古': u'呼和浩特', u'河北': u'石家庄',
            u'甘肃': u'兰州', u'青海': u'西宁', u'陕西': u'西安', u'宁夏': u'银川', u'河南': u'郑州',
            u'山东': u'济南', u'山西': u'太原', u'安徽': u'合肥', u'湖北': u'武汉', u'湖南': u'长沙',
            u'江苏': u'南京', u'四川': u'成都', u'贵州': u'贵阳', u'云南': u'昆明', u'广西': u'南宁',
            u'西藏': u'拉萨', u'浙江': u'杭州', u'江西': u'南昌', u'广东': u'广州', u'福建': u'福州',
            u'台湾': u'台北', u'海南': u'海口', u'香港': u'香港', u'澳门': u'澳门'
}


if __name__ == '__main__':
    total_question = len(capitals)
    total_students = 6
    china_capital_quiz = RandomQuizGenerator.RandomQuizGenerator(capitals, total_students, total_question)
    china_capital_quiz.run()

是或不是要舒服很多?但为啥这么短呢?因为你把题目封装了,封装将详细的法子隐藏了,所以Class只须要被调用就是;具体的兑现,只必要操作一个相当的小的文书正是了。

继承、多态

恐怕有同学会说:『小编用经过去改一下输入输出也得以做那件事啊』。嘿嘿,好像是足以;但是1旦你面对的不是多个地理老师吗?假如是还有别的老师,选用题的选项不止几个如何做?又拿原来做好的进程文件去改;照旧用Class中拉3个subclass出来啊?很醒目答案是subclass越来越好。首先能够再而三原来的Class,然后还足以在那些Class上做更改。整个程序也会更清晰。

4 Conclusion

由此咯,学习Class,有一个格局正是把温馨原先写的这多少个经过改一下,那样能够更加好的体验哟

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图
Copyright @ 2010-2019 亚洲必赢app官方下载 版权所有