类
class Dog:
# 特殊方法,创建实例时自动调用,init,否则无法自动调用
def init(self, name, age):
self.name = name
self.age = age
# 指定默认值属性(这里的属性也可以是类,此处不再演示)
self.size = ‘big’
# 定义一个小狗坐下的方法
def sit(self):
print(f"{self.name} is now sitting")
def roll_over(self):
print(f"{self.name} rolled over!")
def update_age(self, age):
if age < 100:
self.age = age
else:
print("age is too big")
创建实例、访问属性、调用方法、属性赋值
my_dog = Dog(‘Willie’, 3)
print(f"my dog name is {my_dog.name}")
my_dog.sit()
my_dog.age = 10
继承 哈士奇,继承Dog类
class SiberianHusky(Dog):
# 初始化父类属性,再初始化自己的属性size
def init(self, name, age):
super().init(self, name, age)
self.size = ‘middle’
# 重写父类方法
def sit(self):
print(f"SiberianHusky is now sitting")
导入类 from 文件名 import 类名1,类名2
from SiberianHusky import SiberianHusky
导入整个模块
import SiberianHusky
导入模块中所有类 from 文件名 import *
from SiberianHusky import *
使用 as 进行别名
from SiberianHusky import SiberianHusky as SH
引入类库,具体类库查询api randint 根据范围生成随机整数
from random import randint
文件读取 open(‘文件名字’) python打开文件不需要进行close,其会在合适时机自动关闭
with open(‘C:\docx\文档-work\笔记.txt’) as file_object:
# 读取文件内容
contents = file_object.read()
# 打印文件内容并去掉空格
print(contents.rstrip())
逐行读取
with open(‘C:\docx\文档-work\笔记.txt’) as file_object:
# 读取文件内容
for line in file_object:
# 消除文件可能存在的换行符
print(line.rstrip())
也可以获取文件的所有行
with open(‘C:\docx\文档-work\笔记.txt’) as file_object:
# 读取文件内容
lines = file_object.readlines()
# 消除文件可能存在的换行符
for line in lines:
print(line.rstrip())
向文件中写入内容,注意第二个参数‘w’,代表已写入模式打开文件 其中 r-读取 w-写入 a-附加 r+ 读写模式
这里的 w 并非只有上述几种参数可选,也可以 open(‘fileName’, encoding=‘utf-8’)以utf8格式打开文件
file_name = ‘C:\docx\文档-work\笔记.txt’
with open(file_name, ‘w’) as file_object:
file_object.write(‘lvhzuocheng love work\n’)
file_object.write(‘jingning love work\n’)
在文件最后附加内容,而不是覆盖,使用参数 a
with open(file_name, ‘a’) as file_object:
file_object.write(‘i append some\n’)
file_object.write(‘you append some also\n’)
异常捕获 else中放try成功执行后需要执行的代码
try:
answer = print(5/0)
except ZeroDivisionError:
# pass代表什么都不做
pass
else:
print(answer)
将数据转换为json格式存储在文件中
import json
numbers = [‘1’, ‘2’, ‘3’]
filename = ‘numbers.json’
with open(filename, ‘w’) as f:
# 将numbers数据转换为json存储在numbers.json文件中 dump写入方法
json.dump(numbers, f)
加载文件中的json数据 load加载方法
filename = ‘numbers.json’
with open(filename) as f:
numbers = json.load(f)
print(numbers)
以上代码综合一段代码
def greet_user():
filename = ‘username.json’
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
username = input(“what is your name?”)
with open(filename, ‘w’) as f:
json.dump(username, f)
print(f"i will remember you if when you come back, {username}“)
else:
print(f"welcome, {username}”)
greet_user()