1 使用类定义装饰器
class Person(object):def __init__(self):self._age = 0@propertydef age(self):return self._age@age.setterdef age(self,newValue):print('触发了吗')self._age = newValuep = Person() print(p.age) # 0 p.age = 20 print(p.age) # 20
2 类属性
class Person():def __init__(self):self._age =10def get_age(self):return self._agedef set_age(self,newValue):self._age = newValueage = property(get_age,set_age)p = Person() print(p._age) # 10 p.set_age(20) print(p._age) # 20
3 上下文管理器
class File():def __init__(self,file_name,file_mode):self.fileName = file_nameself.fileMode = file_modedef __enter__(self):print('进入上文方法')self.file = open(self.fileName,self.fileMode)return self.filedef __exit__(self, exc_type, exc_val, exc_tb):print('进入下午方法')self.file.close()if __name__ =="__main__":with 语句 结合上下文 管理器对象使用 with File('log.txt','r') as file:file_data = file.read()print(file_data)
4 使用contextmanager装饰器
@contextmanager def my_open(path,mode):try:file = open(path,mode)yield fileexcept Exception as e:print(e)finally:file.close()with my_open('log.txt','r') as file:file_data = file.read()print(file_data)
5 生成器的创建方式:
my_generator = (i*2 for i in range(3)) print(my_generator) print(next(my_generator)) # 0 print(next(my_generator)) # 2 print(next(my_generator)) # 4
my_generator = (i*2 for i in range(3))while True:try:value = next(my_generator)print(value) #0 2 4 except Exception as e:break
def my_generator():for i in range(10):print('开始生成数据')yield i # 函数中有yieid 代表生成了生成器result = my_generator()while True:try:value = next(result)print(value)except Exception as e:breakfinally:print('执行完了')6 悲波那契数列 def f(num):a = 0b = 1current_index = 0while current_index < num:result = aa,b = b, a+bcurrent_index += 1yield resultf1 = f(5) for value in f1:print(value)
7 关于深浅拷贝
cory为浅拷贝函数
import copya = 10b = copy.copy(a)print(id(a)) 140705368775384print(id(b)) 140705368775384b = 20print(a) # 10 print(b) # 20
list1 = [1,2,3,4,5,6,7] list2 = copy.copy(list1)print(id(list1)) # 1980239763648 print(id(list2)) # 1980239761792list2.append(8)print(list2) # [1, 2, 3, 4, 5, 6, 7, 8]print(list1) # [1, 2, 3, 4, 5, 6, 7]
list1 = [1,2,3,4,5,6,7,[8,9,10]]list2 = copy.copy(list1)print(id(list1)) # 1980239763648 print(id(list2)) # 1980239761792list2[7][1] = 11print(list2) # [1, 2, 3, 4, 5, 6, 7, [8, 11, 10]]print(list1) # [1, 2, 3, 4, 5, 6, 7, [8, 11, 10]]
深拷贝 :deepcopy
list1 = [1,2,3,4,5,6,7,[8,9,10]]list2 = copy.deepcopy(list1)print(id(list1)) # 1980239763648 print(id(list2)) # 1980239761792list2[7][1] = 11print(list2) # [1, 2, 3, 4, 5, 6, 7, [8, 11, 10]]print(list1) # [1, 2, 3, 4, 5, 6, 7, [8, 9, 10]]
8 正则表达式 re模块
import re
result = re.match(正则表达式,要匹配的字符串)
result.group()