- type,object和class的关系:
- type -> class -> object
- object是最顶层基类
- type生成所有的类
- type生成类:
def fn(self,name="world"):
print(name)
Hello = type('Hello',(object,),dict(hello=fn))
h = Hello()
h.hello()
- 抽象类
import abc
from collections.abc import Sized
class PersionBase(metaclass=abc.ABCMeta):
def get(self,key):
pass
@abc.abstractmethod
def set(self,key,value):
pass
class Persion(PersionBase):
def set(self,key,value):
pass
xiaoming = Persion()
- 两种访问私有属性的方法:
class Persion:
def __init__(self,name):
self.name = name
self.__age = 18
def get_age(self):
print(self.__age)
xiaoming = Persion("xiaoming")
print(xiaoming.get_age())
print(xiaoming._Persion__age)
- super函数
class Persion:
def get(self):
print("Persion")
class Woman(Persion):
def get(self):
print("Woman")
super().get()
class Man(Persion):
def get(self):
print("Man")
super().get()
class XiaoMing(Man):
def get(self):
print("XiaoMing")
super().get()
xiaoming = XiaoMing()
xiaoming.get()
"""
1. 既然我们重写了get,为什么还要调用super呢?
重用代码
2. super到底执行顺序是什么?
按照mro的顺序来调用
"""
- with语句
"""
上下文管理器协议:
"""
class Sample:
def __enter__(self):
# 获取资源
print("enter")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# 释放资源
print("exit")
def do_something(self):
print("do something")
with Sample() as sample:
sample.do_something()
"""
输出:
enter
do something
exit
"""
- contextlib简化上下文管理器
"""
通过@contextlib.contextmanager将一个函数变为上下文管理器函数
@contextlib.contextmanager实现了__enter__和__exit__方法
"""
import contextlib
@contextlib.contextmanager
def file_open(file_name):
print("file open")
yield {}
print("file close")
with file_open("xxx.txt") as f:
print("file processing")
- 序列
所谓序列,指的是一块可存放多个值的连续内存空间,这些值按一定顺序排列,可通过每个值所在位置的编号(称为索引)访问它们。
在 Python 中,序列类型包括字符串、列表、元组、集合和字典,这些序列支持以下几种通用的操作,但比较特殊的是,集合和字典不支持索引、切片、相加和相乘操作。
-
list + += extend的区别
- +: 是生成一个新的列表(地址id发送改变)
- extend: 是将列表的成员取出来加到原列表中去,地址id不变
- +=: 内部使用了__iadd__魔法方法,而__iadd__内部调用了extend方法
-
实现可切片的对象
__getitem__是实现切片的关键。- alist[::]: 返回原列表中所有元素的新列表
- alist[::-1]: 返回原列表中所有元素的逆序列表
- alist[::2]: 获取偶数位置元素
- alist[1::2]: 获取奇数位元素
import numbers
class Group:
# 支持切片操作
def __init__(self,group_name,company_name,staffs):
self.group_name = group_name
self.company_name = company_name
self.staffs = staffs
def __reversed__(self):
# 实现Group可以翻转:reversed(Group)
self.staffs.reversed()
def __getitem__(self, item):
# 实现切片的关键
cls = type(self)
if isinstance(item,slice):
return cls(group_name=self.group_name,company_name=self.company_name,staffs=self.staffs[item])
elif isinstance(item,numbers.Integral):
return cls(group_name=self.group_name,company_name=self.company_name,staffs=[self.staffs[item]])
def __len__(self):
# 实现Group可以获取长度:len(Group)
return len(self.staffs)
def __iter__(self):
# 实现Group可以迭代:可以用for循环遍历
return iter(self.staffs)
def __contains__(self, item):
# 实现Group可以判断元素是否存在:xx in Group
if item in self.staffs:
return True
return False
staffs = ["zhangsan","lisi","wangwu"]
group = Group(group_name="HIO",company_name="calix",staffs=staffs)
print(group[:2])
# <__main__.Group object at 0x7fbadc200310>
print(len(group))
# 3
print("lisi" in group)
# True
for users in group:
print(users)
- bisect维护已排序序列
import bisect
# 用来处理已排序的序列,用来维持已排序的序列,升序
# 二分查找
inter_list = []
bisect.insort(inter_list,3)
bisect.insort(inter_list,5)
bisect.insort(inter_list,1)
bisect.insort(inter_list,9)
print(inter_list)
# [1, 3, 5, 9]
- 列表推导式
# 列表生成式性能高于列表操作
odd_list = [i for i in range(21) if i % 2 == 1]
print(odd_list)
# [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
- 生成器表达式式:
odd_list = (i for i in range(21) if i % 2 == 1)
print(odd_list)
# <generator object <genexpr> at 0x7ffa57760a50>
- set、 fronzenset
无序的,不可重复的。fronzenset:不可变的。 - set和dict的实现原理:
dict查找的性能远远大于list - dict和defaultdict的区别:
dict如果key不存在读取时会报错,defaultdict会给key设置默认值。
2万+

被折叠的 条评论
为什么被折叠?



