zoukankan      html  css  js  c++  java
  • 属性极其应用(分页显示)

    属性极其应用(分页显示)

    • 定义:
      • @property装饰器
      • 只有一个self参数
    • 执行:
      • 对象.方法 ,不用加括号

    分页显示

    #**传统代码**
    def func():
        '''
        主函数
        :return:
        '''
        num = int(input("请输入要浏览的页码:"))#大于0切合法
        star_info = (num-1)*10
        end_info =  num * 10
        with open("shops",'r',encoding = 'utf-8') as f:
            a = f.readline()
            lis = []
            count = 0
            for line in f:
                count += 1
                if count >= star_info:
                    lis.append(line)
                if count >= end_info:
                    break
        print("第%s页的内容为"%(num),lis)
    func()
    
    
    #**面向对象的代码**
    class Page:
        def __init__(self,total_count,current_page,per_page_count = 10):
            self.total_count = total_count
            self.per_page_count = per_page_count
            self.current_page = current_page
    	@property #属性的体现
        def start_index(self):
            return (self.current_page - 1)*self.per_page_count
    	@property #属性的体现
        def end_index(self):
            return self.current_page*self.per_page_count
    
    USER_LIST = []
    for i in range(321):
        USER_LIST.append("yang-%s"%(i,))
    
    #请实现分页显示
    current_page = int(input("请输入要查看的页码:"))
    P = Page(321,current_page) #还得手动计算总页码
    data_list = USER_LIST[P.start_index:P.end_index]#因为加了属性的装饰器所以start_index()、start_index()后的括号可以去掉
    for item in data_list:
        print(item)
    '''
    思考:
    与传统的分页读取相比
    其可用性更强。
    那么何时要用到类呢?
    我认为是在单一函数无法或者很难去解决一个问题时,
    需要多个函数,而这些函数类型相似或者需要共用一个或几个参数时
    可以考虑用类将函数分类。
    '''
    
  • 相关阅读:
    LeetCode "Median of Two Sorted Arrays"
    LeetCode "Distinct Subsequences"
    LeetCode "Permutation Sequence"

    LeetCode "Linked List Cycle II"
    LeetCode "Best Time to Buy and Sell Stock III"
    LeetCode "4Sum"
    LeetCode "3Sum closest"
    LeetCode "3Sum"
    LeetCode "Container With Most Water"
  • 原文地址:https://www.cnblogs.com/yangzilaing/p/13743164.html
Copyright © 2011-2022 走看看