| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2567 人关注过本帖
标题:请教如何把代码装封在函数或者类里面呢?
只看楼主 加入收藏
LanXX
Rank: 1
等 级:新手上路
帖 子:17
专家分:0
注 册:2019-8-5
结帖率:16.67%
收藏
已结贴  问题点数:10 回复次数:9 
请教如何把代码装封在函数或者类里面呢?
下面代码如何装封会比较好呢?有什么好的装封思路呢?求大神指导一下,十分感谢!

import requests
import json

print('''
5分钟,评估你的单词量
评估过程包括三步:
1. 选择适合你的出题范围
2. 通过50个单词得到你的大致词汇量范围
3. 检验你是否真的掌握你在第二步中选择的单词''')

url = 'https://www.'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'}

res = requests.get(url,headers=headers)
words = res.json()

list = []
types = words['data']
for type in types:
    list.append(type[0])

print('''请输入你选择的词库编号,按Enter确认
1,GMAT  2,考研  3,高考  4,四级  5,六级
6,英专  7,托福  8,GRE  9,雅思  10,任意
''')
choice = int(input('>'))
choice = list[choice-1]
print(choice)

test = requests.get('https://www.'+choice,headers=headers)
test_json = test.json()

test_word = []
words_know = []
not_know = []
n = 0

for i in test_json['data']:
    danci = i['content']
    n = n + 1
    print(f'\n第{n}个单词{danci}是否认识,如果认识请按y,如果不认识请按n,输入Esc结束此阶段')
    answer = input('>')
    if answer == 'y':
        test_word.append(danci)
        words_know.append(i)
    elif answer == 'n':
        not_know.append(i)

    elif answer == 'Esc':
        break
    else:
        print('\n输入错误,请按提示输入。')

right = 0
wrong = []
for i in words_know:
    print('--------------------------------')
    print('A.'+ i['definition_choices'][0]['definition'])
    print('B.'+ i['definition_choices'][1]['definition'])
    print('C.'+ i['definition_choices'][2]['definition'])
    print('D.'+ i['definition_choices'][3]['definition'])
    xuan = input('请输入你的选择:')
    print('--------------------------------\n')
    dic = {'A':i['definition_choices'][0]['pk'],'B':i['definition_choices'][1]['pk'],'C':i['definition_choices'][2]['pk'],
    'D':i['definition_choices'][3]['pk']}
    if dic[xuan] == i['pk']:
        right = right + 1
    else:
        wrong.append(i['content'])
print('本次测试小结:')
print(f'50个单词里面,有{len(test_word)}单词你是认识,有'+str(50-int(len(test_word)))+f'单词你是不认识的,在认识的单词里面,你做对了{right}个,做错了'+str(right-int(len(test_word)))+'个,请继续努力!')

[此贴子已经被作者于2020-2-3 12:30编辑过]

搜索更多相关主题的帖子: 认识 append 单词 print 输入 
2020-02-03 12:23
wp231957
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
来 自:神界
等 级:贵宾
威 望:423
帖 子:13688
专家分:53332
注 册:2012-10-18
收藏
得分:10 
回复 楼主 LanXX
你想封装到神马程度,比如,哪些是必须面对用户的
哪些用户不必晓得

DO IT YOURSELF !
2020-02-04 13:48
LanXX
Rank: 1
等 级:新手上路
帖 子:17
专家分:0
注 册:2019-8-5
收藏
得分:0 
回复 2楼 wp231957
大神你好,一般装封思路大概是怎么样,一般会装封到怎么样了,因为我是自学的,一直不太懂如何装封,求大神展示一下吗,十分谢谢!
2020-02-06 12:13
wp231957
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
来 自:神界
等 级:贵宾
威 望:423
帖 子:13688
专家分:53332
注 册:2012-10-18
收藏
得分:0 
回复 3楼 LanXX
我只会封装函数
而大神们封装的是类

DO IT YOURSELF !
2020-02-06 13:07
LanXX
Rank: 1
等 级:新手上路
帖 子:17
专家分:0
注 册:2019-8-5
收藏
得分:0 
回复 4楼 wp231957
嗯 大神 那你可以装封成函数让我学习一下吗?十分感谢!
2020-02-06 16:12
林月儿
Rank: 16Rank: 16Rank: 16Rank: 16
来 自:湖南
等 级:版主
威 望:138
帖 子:2277
专家分:10647
注 册:2015-3-19
收藏
得分:0 
大神说得对,封装成函数就要关心这个函数功能,入参,返回值
一般会对复杂任务细分步骤层层封装,因为任务复杂度不同,就要考虑函数功能的“粒度”
也就是灵活性,所谓船大难掉头就是这个道理
科学规划好封装流程,至于用面向对象还是面向过程的方式实现还是要考虑具体实施方案的

剑栈风樯各苦辛,别时冰雪到时春
2020-02-06 16:42
wp231957
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
来 自:神界
等 级:贵宾
威 望:423
帖 子:13688
专家分:53332
注 册:2012-10-18
收藏
得分:0 
回复 5楼 LanXX
大概弄了一下,你自己再完善一下,:

程序代码:
import requests
import json



def getwords(url):
    headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'}
    res = requests.get(url,headers=headers)
    return res.json()

def gettest(url,choice):
    headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'}
    res = requests.get(url+choice,headers=headers)
    return res.json()

def testa(test_json,not_know,words_know,test_word,n):
    for i in test_json['data']:
     danci = i['content']
     n = n + 1
     print(f'\n第{n}个单词{danci}是否认识,如果认识请按y,如果不认识请按n,输入Esc结束此阶段')
     answer = input('>')
     if answer == 'y':
         test_word.append(danci)
         words_know.append(i)
     elif answer == 'n':
         not_know.append(i)
     elif answer == 'Esc':
         break
     else:
         print('\n输入错误,请按提示输入。')
         
def testb(words_know,right,wrong):
     for i in words_know:
        print('--------------------------------')
        print('A.'+ i['definition_choices'][0]['definition'])
        print('B.'+ i['definition_choices'][1]['definition'])
        print('C.'+ i['definition_choices'][2]['definition'])
        print('D.'+ i['definition_choices'][3]['definition'])
        xuan = input('请输入你的选择:')
        print('--------------------------------\n')
        dic = {'A':i['definition_choices'][0]['pk'],'B':i['definition_choices'][1]['pk'],
                'C':i['definition_choices'][2]['pk'],'D':i['definition_choices'][3]['pk']}
        if dic[xuan] == i['pk']:
            right = right + 1
        else:
            wrong.append(i['content'])
         
         
def main():        
    print('''
          5分钟,评估你的单词量
          评估过程包括三步:
          1. 选择适合你的出题范围
          2. 通过50个单词得到你的大致词汇量范围
          3. 检验你是否真的掌握你在第二步中选择的单词''')
    url = 'https://www.'
    words=getwords(url)
    list = []
    types = words['data']
    for type in types:
        list.append(type[0])

    print('''请输入你选择的词库编号,按Enter确认
          1,GMAT  2,考研  3,高考  4,四级  5,六级  6,英专  7,托福  8,GRE  9,雅思  10,任意''')
    choice = int(input('>'))
    choice = list[choice-1]
    print(choice)

    url='https://www.'
    test_json =gettest(url,choice)

    test_word = []
    words_know = []
    not_know = []
    n=0
    testa(test_json,not_know,words_know,test_word,n)

    right=0
    wrong = []
    testb(words_know,right,wrong)
    print('本次测试小结:')
    print(f'50个单词里面,有{len(test_word)}单词你是认识,有'+str(50-int(len(test_word)))+f'单词你是不认识的,在认识的单词里面,你做对了{right}个,做错了'+str(right-int(len(test_word)))+'个,请继续努力!')
    
if __name__==main():
    main()    


DO IT YOURSELF !
2020-02-06 21:01
wp231957
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
来 自:神界
等 级:贵宾
威 望:423
帖 子:13688
专家分:53332
注 册:2012-10-18
收藏
得分:0 
对一楼代码和七楼代码进行了一些改正和修正,尝试着进行了类的封装:楼主将就着看一下吧

程序代码:
import requests,json

class Exam(object):
    def __init__(self,urla,urlb):
        self.urla=urla
        self.urlb=urlb
        self.headers={'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'}
        self.test_word = []
        self.words_know = []
        self.not_know = []
        self.n=0
        self.right=0
        self.wrong = []
        self.choice=1
        self.choicestr='''请输入你选择的词库编号,按Enter确认
                          1,GMAT  2,考研  3,高考  4,四级  5,六级  6,英专  7,托福  8,GRE  9,雅思  10,任意'''
        self.startstr='''
          5分钟,评估你的单词量
          评估过程包括三步:
          1. 选择适合你的出题范围
          2. 通过50个单词得到你的大致词汇量范围
          3. 检验你是否真的掌握你在第二步中选择的单词'''
    def getwords(self):
        return requests.get(self.urla,headers=self.headers).json()
   
    def gettest(self,choice):
        return requests.get(self.urlb+choice,headers=self.headers).json()
        
    #选择自己想测试的词库    
    def setchoice(self):
        words=self.getwords()
        lst = []
        types = words['data']
        for type in types:
           lst.append(type[0])
        print(self.choicestr)   
        choice = int(input('>'))
        self.choice = lst[choice-1]
        print(self.choice)
    # A 阶段测试         
    def testa(self):
        self.setchoice()
        test_json =self.gettest(self.choice)
        for i in test_json['data']:
            danci = i['content']
            self.n = self.n + 1
            print(f'\n第{self.n}个单词{danci}是否认识,如果认识请按y,如果不认识请按n,输入Esc结束此阶段')
            answer = input('>')
            if answer == 'y':
                self.test_word.append(danci)
                self.words_know.append(i)
            elif answer == 'n':
                self.not_know.append(i)
            elif answer.lower() == 'esc':
                break
            else:
                print('\n输入错误,请按提示输入。')
    # B 阶段测试     
    def testb(self):
        for i in self.words_know:
            print(i['content'])
            print('--------------------------------')
            print('A.'+ i['definition_choices'][0]['definition'])
            print('B.'+ i['definition_choices'][1]['definition'])
            print('C.'+ i['definition_choices'][2]['definition'])
            print('D.'+ i['definition_choices'][3]['definition'])
            xuan = input('请输入你的选择:')
            print('--------------------------------\n')
            dic = {'A':i['definition_choices'][0]['pk'],'B':i['definition_choices'][1]['pk'],
                   'C':i['definition_choices'][2]['pk'],'D':i['definition_choices'][3]['pk']}
            if dic[xuan.upper()] == i['pk']:
                self.right = self.right + 1
            else:
                self.wrong.append(i['content'])
    #最后评分阶段           
    def pingfen(self):
        print('本次测试小结:')
        print(f'50个单词里面,有{len(self.test_word)}单词你是认识,有'+
              str(50-int(len(self.test_word)))+
              f'单词你是不认识的,在认识的单词里面,你做对了{self.right}个,做错了'+
              str(int(len(self.test_word))-self.right)+'个,请继续努力')    
         
def main():        
    urla = 'https://www.'
    urlb='https://www.'
    exam=Exam(urla,urlb)  
    print(exam.startstr)
    exam.testa()
    print("进行下一阶段的测试")
    exam.testb()
    print("下面进行评分")
    exam.pingfen()
    
if __name__=="__main__":
    main()    


DO IT YOURSELF !
2020-02-08 08:41
LanXX
Rank: 1
等 级:新手上路
帖 子:17
专家分:0
注 册:2019-8-5
收藏
得分:0 
回复 7楼 wp231957
太感谢大神了,谢谢!!!
2020-02-12 17:32
Emperor翔
Rank: 1
等 级:新手上路
帖 子:2
专家分:0
注 册:2020-2-13
收藏
得分:0 
楼上大神啊
2020-02-13 11:52
快速回复:请教如何把代码装封在函数或者类里面呢?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.024772 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved