持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第22天,点击查看活动详情
Python专题的文章收录于专栏:Python专栏
4. 自定义函数
1. 函数的定义
def 函数名 (参数):
函数体
return语句
示例:
def math(x):
y = x**2+x
return y
2. 函数的调用
a = math(10)
print(a)
3. 函数的参数
- 位置参数
def menu(a,b):
print(a,b)
menu('花生','拉面') #按默认位置传入参数
menu(b='拉面',a='花生') #按声明传入参数
- 默认参数
def menu(a,b,c='水'):
print(a,b,c)
menu('花生','拉面') #c默认为'水'
menu('花生','拉面','茶') #c被声明为'茶'
- 不定长参数
def menu(*d):
print(d)
menu('花生','拉面') #打印元素为花生和拉面的元组
menu('花生','拉面','水') #打印元素为花生、拉面和水的元组
4. 函数的返回值
#返回一个值
def math1(a,b):
c = a+b
return c
#返回多个值
def math2(a,b):
c = a+b
return a,b,c #返回类型为元组
5. 函数的嵌套
#最常见的嵌套
print(len('我和你'))
#在函数定义中嵌套
rent = 1000
def cost(a):
money = 80*a
return money
def sum_cost(a):
sum = rent+cost(a) #将cost()函数嵌套与sum_cost()函数中
return sum_cost
5. 类
1. 类的创建
示例:
class Computer:
self.screen = True
def start(self): #self:定义时不能省,调用时可忽略
print('电脑开机中')
在内部调用属性或方法时,采用self.属性名和self.方法名的形式
2. 类的调用
my_computer = Computer() #类的实例化
print(my_computer.screen) #调用实例化对象的属性
my_computer.start() #调用实例化对象的方法
3. 类的初始化方法(构造函数)
#无参构造
class Computer:
def __init__(self):
self.screen = True
#有参构造
class Computer:
def __init__(self,screen,mouse):
self.screen = screen
self.mouse = mouse
4. 类的继承
语法:class A(B):
A为子类,B为父类
所有的实例,都属于根类object
多层继承(深度扩展):子类创建的实例都可以调用所有层级父类的属性和方法
多重继承(宽度扩展):class A(B,C,D)
5. 类的定制
对子类进行 新增代码(新增属性或方法) 或 重写代码
6. 类的特殊方法
__str__()
打印对象即可打印出其返回值
class Book:
def __init__(self):
self.author='吴承恩'
seil.name='《西游记》'
def __str__(self):
return self.name
book1=Book()
print(book1) #直接打印__str__()的返回值
6. 文件操作
1. 编码和解码
用法:
'你想编码的内容'.encode('你使用的编码表')
'你想解码的内容'.decode('你使用的编码表')
2. 文件读写
- open()
file1 = open('路径或地址' , '打开方式' , encoding='编码表')
第一个参数:
1.open('C:\Users\Ted\Desktop\test\abc.txt') #\是转义符,故将\替换成\
2.open(r'C:\Users\Ted\Desktop\test\abc.txt') #在路径前加字母'r'则无需替换
第二个参数:
打开模式 'r'表示读;'w'表示写;'a'表示追加
| r | r:只读 | rb:二进制只读 | r+:读写 | rb+:二进制读写 |
|---|---|---|---|---|
| w | w:只写 | wb:二进制只写 | w+:读写 | wb+:二进制读写 |
| a | a:追加 | ab:二进制追加 | a+:追加可读 | ab+:二进制追加且可读 |
- read()
file1 = open('abc.txt','r')
filecontent = file1.read() #读取文件内容
- write()
file1 = open('abc.txt','w')
file1.write('hhhhhhh') #重写文件
file2 = open('efg,txt','a')
file2.write('hhhhhhh') #追加编写文件
当写入的数据是图片或音频时,用二进制方式,即'wb'
- close()
#第一种打开方式,需要close()关闭文件
file1 = open('abc.txt','r')
file = file1.read()
file1.close()
#第二种打开方式,不需要close()关闭文件
with open('abc.txt','r') as file1
- readlines()
file_lines=file1.readlines() #逐行读取
得到的是一个列表,每个元素代表一行,且每个元素最后有换行符
- writelines()
file1.writelines('hhhhh') #参数也可以是列表