上一页 1 ··· 21 22 23 24 25 26 27 28 29 ··· 52 下一页
摘要: Python proprety() 基础 一、问题 管理对象的属性。 二、解决方案 定义为property。 实例:增加对属性的类型检查。 class Person: def __init__(self, first_name): self._first_name = first_name # Ge 阅读全文
posted @ 2021-12-21 10:11 做梦当财神 阅读(164) 评论(0) 推荐(0)
摘要: 单前导下划线:_var 单末尾下划线:var_ 双前导下划线:__var 双前导和末尾下划线:__var__ 单下划线:_ 文章结尾有”速查表“。 一、单前导下划线_var 以单下划线开头的变量或方法理论上仅供内部使用,执行时不会强制执行。 class Test: def __init__(self 阅读全文
posted @ 2021-12-20 17:20 做梦当财神 阅读(142) 评论(0) 推荐(0)
摘要: Python format() 基础。 一、问题 通过format()函数和字符串方法使对象能支持自定义的格式化。 二、解决方案 为了自定义字符串的格式化,需要在类上面定义__format__()。 _formats = { 'ymd' : '{d.year}-{d.month}-{d.day}', 阅读全文
posted @ 2021-12-20 12:44 做梦当财神 阅读(91) 评论(0) 推荐(0)
摘要: 一、问题 当代码要创建大量(上百万)对象,导致内存占用很大。 二、解决方案 给类添加__slots__属性减少实例占用内存。 class Date: __slots__ = ['year', 'month', 'day'] def __init__(self, year, month, day): 阅读全文
posted @ 2021-12-17 15:38 做梦当财神 阅读(72) 评论(0) 推荐(0)
摘要: 一、问题 求复杂序列中的最大、最小值。 二、解决问题 operator.itemgetter() 解析 from operator import itemgetter info = [ {'name': 'wangke', 'age': 30, 'weight': 65}, {'name': 'wa 阅读全文
posted @ 2021-12-16 15:45 做梦当财神 阅读(212) 评论(0) 推荐(0)
摘要: 一、问题 求复杂序列中的最大、最小N个元素。 二、解决问题 heapq 模块有两个函数:nsmallest、nlargest()。 import heapq # 堆排序 nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] print(heapq.nlarge 阅读全文
posted @ 2021-12-16 14:47 做梦当财神 阅读(188) 评论(0) 推荐(0)
摘要: 一、问题 保留最后几个元素。 二、解决方案 deque(maxlen=N)会新建一个固定大小的队列。 当新元素加入已满的队列,最老的元素会被移除。 from collections import deque q = deque(maxlen=3) q.append(1) print(q) q.app 阅读全文
posted @ 2021-12-15 16:55 做梦当财神 阅读(394) 评论(0) 推荐(0)
摘要: 一、问题 检查字符串的开头或结尾。 二、解决方案 startswith()、endswith()。 filename = 'test.txt' print(filename.endswith('.txt')) print(filename.startswith('file.')) 输出: True 阅读全文
posted @ 2021-12-15 10:21 做梦当财神 阅读(307) 评论(0) 推荐(0)
摘要: 一、描述 os.listdir() 用于返回指定文件夹包含的文件或文件夹的名字列表。 不包括.和..即使在文件夹中。 只支持Unix、Windows。 Python2针对目录中的中文,需要unicode()转换,Python3没有该方法,不需要。 二、语法 os.listdir(path) path 阅读全文
posted @ 2021-12-15 09:50 做梦当财神 阅读(1086) 评论(0) 推荐(0)
摘要: 一、del 1. del List lst = ['wangke', 'wangyan', 'wangying', 'qinlu'] del lst[3] print(lst) 输出: ['wangke', 'wangyan', 'wangying'] 删除变量。 lst = ['wangke', 阅读全文
posted @ 2021-12-14 13:53 做梦当财神 阅读(380) 评论(0) 推荐(0)
上一页 1 ··· 21 22 23 24 25 26 27 28 29 ··· 52 下一页