33 类
class Dog(): def __init__(self,name,age): self.name =name self.age = age def sit(self): print(self.name+''+self.age)dog = Dog('jeety',24)print(dog.name)
34 类 汽车里程表
class Car(): def __init__(self,make,model,year): self.make = make self.model = model self.year = year def getCarName(self): print(self.model)car = Car('audi','ad4',2016)print(car.make)
35 子类方法 init ()
class Car(): def __init__(self,name): self.name = nameclass Elastic(Car): def __init__(self, name): super().__init__(name)myTesla = Elastic('tesla')print(myTesla.name)
36 class实例
class Car(): def __init__(self,make,name,color): self.make = make self.name = name self.color = color def getCarName(self): print('获取车的名字为'+self.name+'获取汽车的颜色'+self.color)class Batery(): def __init__(self,batery='60'): self.batery = batery def discribe_batery(self): print('This car has'+str(self.batery)+'batery')class Elatrity(Batery): def __init__(self, batery): super().__init__(batery) self.batery = Batery()elatrity = Elatrity('100')print(elatrity.discribe_batery())
37 文件和异常
f = open('file.txt',mode="w",encoding='utf-8')print(f)f.write('叫我詹躲躲\n')f.write('叫我詹躲躲1\n')f.close()
38 将数据存入json文件
import jsonnumbers = [1,2,23,3,4,5,6,7,87]filename = 'numbers.json'with open(filename,'w') as f_obj: json.dump(numbers,f_obj)
39 保存和读取用户生成的数据
import jsonusername = input('存储输入的数据')filename = 'numbers.json'with open(filename,'w') as f_obj: json.dump(username,f_obj)
40 读取用户输入的信息
import jsonfilename = 'numbers.json'with open(filename) as f_obj: username = json.load(f_obj) print('Welcome back',username)
41 输入和合并数据
import jsonfilename = 'numbers.json'try: with open(filename) as f_obj: username = json.load(f_obj)except FileNotFoundError: username = input('存储输入的数据') with open(filename,'w') as f_obj: json.dump(username,f_obj)else: print('Welcome back',username)
42 封装成为一个函数
import jsondef get_username(): filename = 'numbers.json' try: with open(filename) as f_obj: username = json.load(f_obj) except FileNotFoundError: return None else: return usernamedef get_greeting(): username = get_username() if username: print('Welcome back',username) else: username = input('存储输入的数据') filename = 'numbers.json' with open(filename,'w') as f_obj: json.dump(username,f_obj) print('Welcome back',username)get_greeting()
43 文件读取
f = open('index.txt',encoding='utf-8')s = f.read()print(s)f.close()
44 文件写入
f = open('index.txt',mode="w",encoding='utf-8')f.write('叫我詹躲躲n')f.write('叫我詹躲躲1n')f.close()
45 第三方库安装和使用
import randomrandom.randint() #随机数import jieba #结巴import wordcloud #词云jieba.lcut('分割中文词语的序列') #分割中文词语的序列word_cloud = wordCloud(font_path='msyh.ttc').generate('分割中文词语') #生成词云对象word_cloud.to_file('123.png') #保存到图片
46 python 里面的类和对象
#面向对象编程class Person: def __init__(self,name,sex,birthday): self.name = name self.sex = sex self.birthday = birthday def say(self,word): print(f'{self.name}说:"{word}"')zhang_san = Person('张三','男','2020202')zhang_san.say('12121')
47.输出 %占位符
lastname = 'hello'firstname = 'world'print('我的名字是%s %s' %(lastname,firstname))
48.常用的格式化字符
%c #字符%s #通过str来格式化%i #有符号十进制整数%d #有符号十进制整数%u #无符号十进制整数%o #八进制整数%x #十六进制整数(小写字母)%e #索引符号(小写e)%E #索引符号(大写E)%f #浮点实数%g #%f和%e的简写%G #%f和%E的简写
49格式化的其他方式 format
name = '老夫子'age = 28print('姓名:{},年龄{}'.format(name,age))#姓名:老夫子,年龄28
50 .匿名函数
50.1lambda 参数1,参数2,参数3:表达式
#特点:#1.使用lambda关键字创建函数#2.没有名字的函数#3.匿名函数冒号后面的表达式有且只有一个,是表达式不是语句#4.自带return
50.2.lambda 示例1
def computer(x,y): #计算两数和 return x+yM = lambda x,y:x+yprint(M(1,2))
50.3.lambda 示例1
result = lambda a,b,c:a*b*cprint(result(12,121,1))
50.4 lambda 三元表达式模拟
age = 15print('可以参军' if age>18 else '继续上学')#直接调用result = (lambda x,y:x if x>y else y)(2,5)
51.递归函数
#阶乘函数def factorial(n): if n==1: return 1 else: return n*factorial(n-1) passprint(factorial(3))
51.1 递归案例 模拟实现 树形结构的遍历
import os 文件操作模块def findFile(file_path): listRs = os.listdir(file_path) 得到该路径所有的文件夹 for fileItem in listRs: full_path = os.path.join(file_path,fileItem) if os.path.isdir(full_path): 判断是否为文件夹 findFile(full_path) else: print(fileItem) pass pass else: returnfindFile('F:\\7.代码学习')
51.1python的内置函数
abs(-27) #绝对值round(21.1123) #浮点近似值pow(2,3) #幂 2**3divmod(10,3) # 商余max(1,2,3,4) #最大值min(1,2,3,4) #最小值sum(1,2,3,4) #求和eval() #动态执行表达式
51.2类型转换函数
int #整型float #浮点型str #字符类型ord #返回对应字符的ASCIIchr #数字转字符 ASCIIbool #booleanbin # 转换二进制hex #转换为十六进制oct #八进制list #元祖转列表tuple #元祖dict #创建字典bytes #转为字节
52.可迭代参数 all
#all 用于判定给定的可迭代参数中的所有元素是否都为TRUE,如果是返回TRUE,否则返回FALSE,除了0,空,False 外都算TRUEdef all(iterable): for ele in iterable: if not ele: return False return Trueli = [1,2,3,4,5,6,False]print(all(li)) ##False
53 可迭代参数 any
#全部为false,返回falsedef any(iterable): for ele in iterable: if ele: return False return Trueli = [0,False,'']print(any(li)) ##False
54.enumerate 列出遍历数据和下标
li = ['a','b','c']for index,item in enumerate(li,7): print(index,item)#改下标7 a8 b9 c
55.set集合 不支持索引和切片,无序不重复
55.1.创建集合1
set1 = {'1','2'}set2 = {'11','1'}#添加 addset1.add('3')#清空 clear()set1.clear()#取差集 differenceset1.difference(set2) ##set1取set1中有的#取交集set1.intersection(set2)#取并集set1.union(set2)set1 | set2#末尾移除set1.pop()#指定移除set1.discard(3)#更新 update 合并一起去重set1.update(set2)
55.2 练习题1 三组数据求和
1-10,20-30,35-40def threeSum(a1,a2,a3): return sum(a1+a2+a3)a1 = list(range(1,11))a2 = list(range(20,31))a3 = list(range(35,41))print(threeSum(a1,a2,a3))
55.3练习题2 大小和尚多少个
def computers(): for i in range(1,101): for j in range(1,34): if i+j==100 and 3*j+i/3 ==100: print('大和尚有{}个,小和尚有{}个'.format(j,i)) passcomputers()#大和尚有25个,小和尚有75个
55.4 练习题3 找出独一无二的数据
li = [1,1,1,2,2,2,2,3,2,2,3,4,2,1,1]def findUnionNumber(li): for item in li: if li.count(item)==1: return item passprint(findUnionNumber(li))
56.字典统计每个元素的次数
dict ={}for key in li: dict[key] = dict.get(key,0)+1print(dict)
56.1.collection包下Counter类统计
from collections import Countera = [1, 2, 3, 1, 1, 2]result = Counter(a)print(result)
56.2.pandas包下的value_counts方法统计
import pandas as pda = pd.DataFrame([[1,2,3], [3,1,3], [1,2,1]])result = a.apply(pd.value_counts)print(result)
56.3.利用set找出独一无二的数据
li = [1,2,3,3,2,3,4,4,5,1,2,1]def uniqueNum(li): set1 = set(li) for i in set1: li.remove(i) set2 = set(li) for j in set2: set1.remove(j) return set1print(uniqueNum(li))
57 面向对象编程 oop
#面向过程编程 根据业务从上到下开始编程#类的结构#类名 属性 方法class People: name = 'zhan', age = 20, def eat(self): print('正在吃饭')#创建对象people = People()people.eat()
在类的内部,使用def定义的为实例方法,第一个参数为self,实例方法归实例所有
57.1 类的实例属性添加
class People: name = 'zhan', age = 20, def eat(self): print('正在吃饭')#创建对象people = People()people.eat()#添加属性people.name2 = 'zhan'people.age2 = 22复制代码
57.2 类的init()方法
class People: # 初始化的操作,实例属性,自动执行 def __init__(self): self.name = 'zhan' self.age = 20 def eat(self): print('正在吃饭')#创建对象people = People()people.eat()
57.3 类的init()使用参数
class People: # 初始化的操作,实例属性,自动执行 def __init__(self, name, age): self.name = name self.age = age def eat(self,food): print(self.name+food)#创建对象people = People('叫我詹躲躲', 20)people.eat('正在吃饭')people.eat('洗澡')people.eat('跑步')
57.4 理解类的self
#类似于js里面的thisclass Person: def eat(self): print(id(self)) pass passperson = Person()person.eat()print(id(person)) #self和对象指向同一个内存地址,self就是对象的引用# <__main__.Person object at 0x0000020864815CC0>
58 魔术方法
#__init__ :初始化实例属性# __str__ :自定义对象的格式# __new__ :对象实例化class Animal: def __str__(self): return '3213213123123' pass passanimal = Animal()print(animal) class Animal: def __str__(self): return '3213213123123' pass pass def __new__(cls,*args,**kwargs): print("----new执行---") return object.__new__(cls) 真正创建对象实例的 passanimal = Animal()print(animal) #__new__ 和__init__的区别#__new__ 类的实例化方法,必须返回实例,否则创建不成功#__init__数据属性的初始化工作,认为是实例的构造方法,接受实例化self并对其进行构造#__new__ 至少一个参数是cls,代表要实例化的类#__new__ 执行要比__init__早
59 案例练习 —— 决战紫禁之巅
# 属性:# name:玩家名称# blood:血量# 方法:# tong() 捅一刀,掉10滴血# kanren() 砍一刀掉15滴血# chiyao() 补血10滴血# __str__打印玩家的状态class Role: def __init__(self,name,blood): self.name = name self.blood = blood pass 砍人 def tong(self,enemy): enemy.blood -=10 info = '【%s】捅了【%s】一刀'%(self.name,enemy.name) print(info) pass 砍人 def kanren(self,enemy): enemy.blood -=15 info = '【%s】砍了【%s】一刀'%(self.name,enemy.name) print(info) pass 吃药 def chiyao(self): self.blood +=10 info = '【%s】吃了一口药,增加10滴血'%(self.name) print(info) pass def __str__(self): return '%s还剩下%s的血量'%(self.name,self.blood)xmcx = Role('西门吹雪',100)ygc = Role('叶孤城',100)while True: if xmcx.blood<=0 or ygc.blood<=0: break print('*********************') xmcx.tong(ygc) xmcx.kanren(ygc) print('*********************') ygc.tong(xmcx) ygc.chiyao() print('*********************') print(xmcx) print(ygc) """*********************【西门吹雪】捅了【叶孤城】一刀【西门吹雪】砍了【叶孤城】一刀*********************【叶孤城】捅了【西门吹雪】一刀【叶孤城】吃了一口药,增加10滴血*********************西门吹雪还剩下50的血量叶孤城还剩下25的血量*********************【西门吹雪】捅了【叶孤城】一刀【西门吹雪】砍了【叶孤城】一刀*********************【叶孤城】捅了【西门吹雪】一刀【叶孤城】吃了一口药,增加10滴血*********************西门吹雪还剩下40的血量叶孤城还剩下10的血量*********************【西门吹雪】捅了【叶孤城】一刀【西门吹雪】砍了【叶孤城】一刀*********************【叶孤城】捅了【西门吹雪】一刀【叶孤城】吃了一口药,增加10滴血*********************西门吹雪还剩下30的血量叶孤城还剩下-5的血量"""
60 实例练习1 水果类
class Fruit: def __init__(self,name,color): self.name = name self.color = color def showColor(self): print('%s的颜色为%s'%(self.name,self.color))apple = Fruit('苹果','红色').showColor()orange = Fruit('橘子','黄色').showColor()watermelen = Fruit('西瓜','绿色').showColor()
61 验证self 就是实例本身
class CkeckSelf: def __str__(self): print(id(self)) pass CkeckSelf().__str__()selfObj = CkeckSelf()print(id(selfObj))
62 定义animal类,输出所有的属性
class Animal: def __init__(self, color, name, age): self.color = color self.name = name self.age = age def run(self): print('%s在跑步'%(self.name)) pass def eat(self): print('%s在吃东西' %(self.name)) pass def __str__(self): return '%s岁的%s的%s'%(self.age,self.color,self.name)cat = Animal('黑色','小猫',2)dog = Animal('白色','小狗',3)cat.run()dog.run()print(cat)print(dog)"""小猫在跑步 小狗在跑步 2岁的黑色的小猫 3岁的白色的小狗"""
64 简易的学生管理系统
1、显示所有学生信息2、新建学生信息3、查询学生信息4、修改学生信息5、删除学生信息0、退出系统
student_data = [ { 'id': 123456, 'name': 'Tom', 'sex': '男', 'address': '迪士尼' }, { 'id': 123457, 'name': 'Jerry', 'sex': '女', 'address': '伦敦' },]
64.1美化显示
def beauty_list(datas): for index, student in enumerate(datas): print(f'序号:{index}', end="t") print(f'姓名:{student["name"]}', end="t") print(f'性别:{student["sex"]}', end="t") print(f'地址:{student["address"]}')
64.2输入名字
def input_name(): while True: name = input('输入名字:').strip() if name: return name else: continue
64.3选择性别
def choose_sex(): print('1(男) | 2(女)') n = input('选择性别') if n == '1': return '男' else: return '女'
64.4显示所有学生信息
def show_all(): beauty_list(student_data)
64.5新建学生信息
def create_student(): sid = random.randint(1000, 10000) name = input_name() sex = choose_sex() address = input('地址:') student = { 'id': sid, 'name': name, 'sex': sex, 'address': address } student_data.append(student)
64.6查询学生信息
def find_student(): name = input_name() for i in student_data: if i['name'] == name: print(i) return else: print('无该学生任何信息')
64.7修改学生信息
def edit_student(): name = input_name() for student in student_data: if student['name'] == name: print(student) student['name'] = input_name() student['sex'] = choose_sex() student['address'] = input('地址:') return else: print('查无此人')
64.8删除学生信息
def delete_student(): name = input_name() for student in student_data: if student['name'] == name: student_data.remove(student) return else: print('查无此人')while True: print(''' ******************** 欢迎使用学生管理系统 1、显示所有学生信息 2、新建学生信息 3、查询学生信息 4、修改学生信息 5、删除学生信息 0、退出系统 ******************** ''' ) op = input('请输入序号:') if op == '1': print(student_data) show_all() elif op == '2': create_student() elif op == '3': find_student() elif op == '4': edit_student() elif op == '5': delete_student() else: print('退出系统') break
想了解更多的Python知识,最新的Python技术,请扫描下方二维码关注小编的微信公众号。

原著是一个有趣的人,若有侵权,请通知删除
还没有人抢沙发呢~