第八章类:
Class Dog:
def __init__(self,name,age):
self.name = name
self.age = age
def sit(self):
print(f"{self.name} is now sitting.")
def roll_over(self):
print(f"{self.name} rolled over!")
方法__init__():自动执行的特殊方法,初始化属性
根据类创建实例:my_dog = Dog('dodo',2)
访问属性:my_dog.name
调用方法:my_dog.sit() my_dog.roll_over()
创建多个实例:your_dog = Dog('willie',3)
直接修改属性的值:my_dog.age = 3
方法修改属性的值:def change(self,n): self.name = n my_dog.change(3)
方法对属性递增:def add(self,n): self.name += n my_dog.add()
继承 子承父类:
Class ElectricDog(Dog):
def __init__(self,name,age):
super().__init__(self,name,age)
重写父类方法:def sit(self): print("它就是不想坐着")
讲实例用作属性:
Class ElectricDog(Dog):
def __init__(self,name,age):
super().__init__(self,name,age)
self.dog = Dog()
my_dog = ElectricDog('dodo',2)
my_dog.dog.sit()
导入单个类:从dog.py中导入Dog
在一个模块中存储多个类:class Dog: class Cat:
从一个模块中导入多个类:from dog import Dog,Cat
导入整个模块:import car
导入模块中的所有类:from dog import *
从一个模块中导入另一个模块:from dog import Dog from cat import Cat
使用别名:from dog import Dog as D my_dog = D("dodo",2)
python标准库:
随机模块random
随机生成之间整数:from random import randint randint(1,6)
随机返回列表或者元组中的元素:from random import choice dogs = ['柯基','法斗'] d = choice(dogs)
第九章文件和异常:
读取整个文件read():
with open('test.txt') as file_object:
contents = file_object.read()
print(contents.rstrip()) #read()多返回一个空行
文件路径:with open('test_files/filename.txt') as file_object: #到python_work文件夹下去找
逐行读取:filename = 'test.txt' with open(filename) as file_object: for line in file_object: print(line)
创建一个包含文件各行内容的列表:↑:lines = file_object.readlines() for line in lines: print(line.rstrip)
使用文件内容:↑:pi_string = '' for line in lines: pi_string += line.strip()
包含一百万位的大型文件:↑:print(f"{pi_string[:52]}...")
写入文件open() write():
filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object.write("i love python")
写入模式('w') 附加模式('a') 读写模式('r+')
写入多行:\n
附加到文件:with open(filename,'a') as file_object: file_object.write("i also love it\n")
异常:try-except代码块
try:
print(5/0)
except ZeroDivisionError:
print("you can not divide by zero!")
try没问题就跳过except,有问题就执行except中的内容
else代码块 try执行成功后执行else:
try:
answer = 5/0
except ZeroDivisionError:
print("you can not divide by zero!")
else:
print(answer)
处理FileNotFoundError异常:
filename = 'test.txt'
try:
with open(filename,encoding = 'utf-8') as f:
contents = f.read()
except FileNotFoundError:
print("找不到文件")
分析文本:
拆分字符串split():
title = "Alice in Wonderland"
title.split()
输出['Alice','in','Wonderland']
计算长度len():p = len(titles)
使用多个文件:def count_words(filename): #放进函数中
for filename in filenames: count_words(filename)
保持静默pass: else: pass
存储数据:
模块json:简单的数据结构存储到文件中,并在程序再次运行中加载文件中的数据
json.dump():
import json
numbers = [2,3,4,5,6]
filename = 'numbers.json' #数字列表指定存储到哪个文件中
with open(filename,'w') as f: #写入模式打开
json.dump(numbers,f) #json.dump()将数字列表存储到文件numbers.json
json.load():
import json
filename = 'numbers.json' #数字列表指定存储到哪个文件中
with open(filename) as f: #读取
numbers = json.load(f) #加载存储在numbers.json中的信息
保存和读取用户生成的数据:
import json
username = input("你叫什么?")
filename = 'numbers.json' #数字列表指定存储到哪个文件中
with open(filename,'w') as f: #写入模式打开
json.dump(numbers,f) #json.dump()将数字列表存储到文件numbers.json
print(f"我会记住你的{username}!")
import json
filename = 'numbers.json' #数字列表指定存储到哪个文件中
with open(filename) as f: #读取
json.dump(numbers,f) #json.dump()将数字列表存储到文件numbers.json
print(f"我会记住你的{username}!")
重构:根据功能组织结构
2020/2/15