Python学习【第九篇】函数
函数
函数是什么?
函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。
在学习函数之前,一直遵循:面向过程编程,即:根据业务逻辑从上而下实现功能,其往往用一段代码来实现指定功能,开发过程中最常见的操作就是复制粘贴,就是将之前实现的代码块复制到现需功能处,如下:
while True: if cpu利用率 > 90%: #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 if 硬盘使用空间 > 90%: #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 if 内存占用 > 80%: #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接
腚眼一看上述代码,if条件语句下的内容可以被提取出来公用,如下:
def 发送邮件(内容) #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 while True: if cpu利用率 > 90%: 发送邮件('CPU报警') if 硬盘使用空间 > 90%: 发送邮件('硬盘报警') if 内存占用 > 80%: 发送邮件('内存报警')
对于上述的两种实现方式,第二种必然比第一种的重用性和可读性要好,其实这就是函数式编程和面向过程编程的区别:
· 函数式:将某功能代码封装到函数中,日后无需重复编写,仅调用函数即可
· 面向对象:对函数进行分类和封装,让开发“更快更好更强...”
函数式编程最重要的是增强代码的重用性和可读性
特性:
·减少重复代码
·使程序变得可扩展
·使程序变得易维护
定义函数
函数的定义主要有如下要点:
· def:表示函数的关键字
· 函数名:函数的名称,日后根据函数名称调用函数
· 函数体:函数中进行一系列的逻辑计算 ==》定义函数,函数体不执行,只有在调用函数的时候才会执行。
· 参数:为函数体提供数据
· 返回值:当函数执行完毕后,可以给调用者返回数据。
返回值
函数是一个功能块,该功能到底执行是否成功与否,需要通过返回值来告知调用者。
def 发送短信(): 发送短信的代码... if 发送成功: return True else: return False while True: # 每次执行发送短信函数,都会将返回值自动赋值给result # 之后,可以根据result来写日志,或重发等操作 result = 发送短信() if result == False: 记录日志,短信发送失败...
注意:
1. 函数在执行过程中只要遇到return语句,就会停止执行并返回结果,所以也可理解为return语句代表函数的结束
def f1 (): print(123) return "111" print(456) r = f1() print r # 输出 123 111
2. 如果未在函数中指定return,那么这个函数的返回值为None
def f2 (): print(123) r = f2() print(r) # 输出 123 None
参数
为什么要有参数?
def CPU报警邮件() #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 def 硬盘报警邮件() #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 def 内存报警邮件() #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 while True: if cpu利用率 > 90%: CPU报警邮件() if 硬盘使用空间 > 90%: 硬盘报警邮件() if 内存占用 > 80%: 内存报警邮件()
def 发送邮件(邮件内容) #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 while True: if cpu利用率 > 90%: 发送邮件("CPU报警了。") if 硬盘使用空间 > 90%: 发送邮件("硬盘报警了。") if 内存占用 > 80%: 发送邮件("内存报警了。")
函数有三种不同的参数:
· 普通参数
######### 定义函数 ######### # name 叫做函数f1的形式参数,简称:形参 def f1(name): print (name) # ######### 执行函数 ######### # 'bourbon' 叫做函数f1的实际参数,简称:实参 f1('bourbon') # 输出 bourbon
· 默认参数
def f1(name, age=18): print(name, age) # 指定参数 f1('bourbon', 19) # 使用默认参数 f1('jerry') # 输出 bourbon 19 jerry 18
注意:如果设置默认参数,那这个默认参数必须放在参数列表的末尾
实际参数默认是一一对应形式参数的,当然也可以指定参数,如下:
def f1(name, age=18): print(name, age) f1(age=20,name='bourbon') # 输出 bourbon 20
· 动态参数
def f1 (*args): print(args,type(args)) # 执行方式一 f1(11,22,33,'bourbon','hhh') # 输出 (11, 22, 33, 'bourbon', 'hhh') <class 'tuple'> --------------------------------------------------------------- # 执行方式二 li = [11,22,33,44,'bourbon','hhh'] f1(li) # 输出 ([11, 22, 33, 44, 'bourbon', 'hhh'],) <class 'tuple'> # 扩展1: f1(li,'666') # 输出 ([11, 22, 33, 44, 'bourbon', 'hhh'], '666') <class 'tuple'> # 扩展2: #当实际参数加"*"时,会将字符串中的每一个元素加到元组里 f1(*li) # 输出 (11, 22, 33, 44, 'bourbon', 'hhh') <class 'tuple'> # 扩展3: a = "bourbon" f1(*a) # 输出 ('b', 'o', 'u', 'r', 'b', 'o', 'n') <class 'tuple'>
def f1(**kwargs): print(kwargs,type(kwargs)) # 执行方式一 f1(name='bourbon',age=18) # 输出 {'age': 18, 'name': 'bourbon'} <class 'dict'> ----------------------------------------------------------------- # 执行方式二 dic = {'k1':'v1','k2':'v2'} f1(kk = dic) #输出 {'kk': {'k1': 'v1', 'k2': 'v2'}} <class 'dict'> #扩展1: f1(**dic) #输出 {'k1': 'v1', 'k2': 'v2'} <class 'dict'>
得出结论:
* 默认将传入的参数,全部放置在元组中,f1(*[11,22,33,44])
** 默认将传入的参数,全部放置在字典中,f1(**{"k1":'v1',"k2":'v2'})
拓展:
def f1(*args,**kwargs): print(args) print(kwargs) f1(11,22,33,44,k1 = "v1",k2 = "v2") # 输出 (11, 22, 33, 44) {'k1': 'v1', 'k2': 'v2'} PS:形式参数必须是*在前面,**在后面。实际参数也必须一一对应
利用动态函数实现format功能
之前说过的格式化输出的方式%s,%d
python中有两种格式化输出方式,还有一种就是format格式化输出
# str.format() 格式化输出 #这里的{0},{1}表示占位符 s1 = "i am {0}, age {1}".format("bourbon",18) print(s1) # 输出 i am bourbon, age 18 s2 = "i am {0},age {1}".format(*["bourbon",18]) print(s2) # 输出 i am bourbon, age 18 s3 = "i am {name},age {age}".format(name = 'bourbon',age =18) print(s3) # 输出 i am bourbon, age 18 dic = {'name':'bourbon','age': 18} s4 = "i am {name},age {age}".format(**dic) print(s4) # 输出 i am bourbon, age 18
拓展:
def f1 (a1,a2): return a1 + a2 def f1 (a1,a2): return a1 * a2 ret = f1(8,8) print(ret) #输出 64
#问题:函数的参数进行传递的时候,传的是引用还是再传一个值 def f1(a1): a1.append(999) li = [11,22,33,44] f1(li) print(li) #输出 [11,22,33,44,999] #由此可见Python在函数的参数传递的时候,传递的是一个引用
全局变量
一个程序的所有的变量并不是在哪个位置都可以访问的。访问权限决定于这个变量是在哪里赋值的。
变量的作用域决定了在哪一部分程序你可以访问哪个特定的变量名称。两种最基本的变量作用域如下:
· 局部变量
def f1(): name = "bourbon" print(name) def f2(): print(name) #这里的name并不能调用到上面的name变量 #自己作用域里的变量只能自己去调用
· 全局变量
NAME = "bourbon" def f1(): age = 18 print(age,NAME) def f2(): age = 19 name = "jerry" print(age,NAME) f1() f2() #输出 18 bourbon 19 jerry #全局变量,所有的作用域都可读(优先读自己作用域内的变量,没有自己定义就引用全局变量)
修改全局变量
# 对全局变量进行重新赋值,需要global NAME = "bourbon" def f1(): age = 18 global NAME #表示,name是全局变量 NAME = "jerry" print(age,NAME) def f2(): age = 19 print(age,NAME) f1() f2() # 输出 18 jerry 19 jerry
PS:当全局变量是一个列表或者是字典时,可修改,但是不能重新赋值
NAME = [11,22,33,44] def f1(): age = 18 NAME.append(999) NAME = "bourbon" print(age,NAME) def f2(): age = 19 print(age,NAME) f1() f2() # 输出 UnboundLocalError: local variable 'NAME' referenced before assignment
注意:以后定义全局变量时,变量名一定要大写
1 def login(username,password): 2 """ 3 用于用户登录 4 :param username:用户输入的用户名 5 :param password: 用户输入的密码 6 :return: True,表示登录成功;False表示登录失败 7 """ 8 f = open("db","r") 9 for line in f: 10 line_list = line.strip().split("|") 11 if line_list[0] == username and line_list[1] == password: 12 return True 13 return False 14 15 16 def register(username,password): 17 """ 18 用于用户注册 19 :param username:用户输入用户名 20 :param password: 用户输入密码 21 :return: 默认返回None 22 """ 23 f = open("db","a") 24 temp ="\n" + username + "|" + password 25 f.write(temp) 26 f.close() 27 28 29 def main(): 30 """ 31 用户选择 32 :return: 默认返回None 33 """ 34 t = input("1:登录;2:注册") 35 if t == "1": 36 user = input("请输入用户名:") 37 pwd = input("请输入密码:") 38 r = login(user,pwd) 39 if r: 40 print("登录成功") 41 else: 42 print("登录失败") 43 elif t == "2": 44 user = input("请输入用户名:") 45 pwd = input("请输入密码:") 46 register(user,pwd) 47 48 main()
内置函数
注:查看详细猛击这里
# abs() 取绝对值 n = abs(-1) print(n) # 输出 1 ----------------------------------- # bool() 布尔值转换 #0,None,"",[],() 这些都为False print(bool()) # 输出 False ------------------------------------- # all&any里面存放一个可迭代的对象 # all() 所有为真才为真 n = all([1,2,3,4,0]) print(n) # 输出 False # any() 只要有一个为真就为真 n = any([0,None,"",3]) print(n) # 输出 True ---------------------------------- # ascii() 自动执行对象的_repr_方法,并获取到它拿到的值 class Foo: def __repr__(self): return"444" n = ascii(Foo()) print(n) # 输出 444 ------------------------------------ # bin() 把十进制转换为二进制 0b表示2进制 # oct() 把十进制转化为八进制 0o表示8进制 # hex() 把十进制转化为十六进制 0x表示16进制 print(bin(5)) # 输出 0b101 print(oct(9)) # 输出 0o11 print(hex(15)) # 输出 0xf ------------------------------------ # utf-8 一个汉字:三个字节 # gbk 一个汉字:两个字节 # bytes() 将字符串转换字节类型 # bytes(只要转换的字符串,按照什么编码) s = "田思寒" n = bytes(s, encoding="utf-8") print(n) # 输出 b'\xe7\x94\xb0\xe6\x80\x9d\xe5\xaf\x92' n = bytes(s, encoding="gbk") print(n) # 输出 b'\xcc\xef\xcb\xbc\xba\xae #转换为字节数组 n = bytearray(s, encoding="utf-8") print(n) # 输出 bytearray(b'\xe7\x94\xb0\xe6\x80\x9d\xe5\xaf\x92') #字节转化成字符串 new_str = str(bytes(s, encoding="utf-8"), encoding="utf-8") print(new_str) # 输出 田思寒 ------------------------------------ # callable() 传的值能不能被调用(被执行) def f1(): pass f1() f2 = 123 print(callable(f1)) # 输出 True print(callable(f2)) # 输出 False -------------------------------------- # ASCII码对应表的关系 # chr()将数字转换成ascii码中对应的字母 # ord()将字母转换成ascii码中对应的数字 r = chr(65) print(r) # 输出 A n = ord(B) print(n) # 输出 66 --------------------------------------- 随机验证码: # 随机生成数字 import random # 随机生成一个1<=i<5的数 i = random.randrange(1,5) print(i) # 随机生成字母 import random i = random.randrange(65,91) c = chr(i) print(c) # 随机生成6位字母 import random li = [] for i in range(6): temp = random.randrange(65,91) c = chr(temp) li.append(c) result = "".join(li) print(result) # 随机验证码升级版v1 import random li = [] for i in range(6): if i == 2 or i == 4: num = random.randrange(0,10) # 在join的时候元素必须是字符串 li.append(str(num)) else: temp = random.randrange(65,91) c = chr(temp) li.append(c) result = "".join(li) print(result) # 随机验证码v2 import random li = [] for i in range(6): r = random.randrange(0,5) if r == 2 or r == 4: num = random.randrange(0,10) li.append(str(num)) else: temp = random.randrange(65,91) c = chr(temp) li.append(c) result = "".join(li) print(result) --------------------------------------------- # compile()将字符串编译成python代码 # eval()执行表达式,并且返回结果 # exec()执行python代码,exec比eval更牛逼的功能,(接受代码或字符串)没有返回值 s = "print(123)" # 编译模式,single(单行的python程序),eval(编译成表达式),exec(编译成python代码一样) # 将字符串编译成python代码 r = compile(s, "<string>","exec") # 执行python代码 exec(r) # 输出 123 s = "8*8" ret = evel(s) print(ret) # 输出 64 --------------------------------------------------- # 反射:delattr,getattr,setattr,hasattr(单独讲解) --------------------------------------------------- # dict() 字典 --------------------------------------------------- # dir() 快速查看一个对象为你提供了哪些功能 # help() 功能详细 --------------------------------------------------- # divmod() 计算商和余,返回的是一个元组 # 计算97/10 的商和余数 r = divmod(97, 10) # 输出 (9,7) print(r[0]) # 输出 9 print(r[1]) # 输出 7 n1,n2 = divmod(100,10) print(n1) print(n2) # 输出 10 0 --------------------------------------------------- # isinstance()用于判断,对象是否是某个类的实例 s = "bourbon" r = isinstance(s, str) print(r) # 输出 True --------------------------------------------------- # filter(函数,可迭代的对象) def f1(a): if a > 22: return True li = [11,22,33,44,55,66] # filter内部,循环第二个参数 # result = [] # for item in 第二个参数: # r = 每次循环执行第一个参数(item) # if r: # result(item) # return result # filter,循环第二个参数,让每个循环元素执行函数,如果函数返回值True,表示元素合法 ret = filter(f1, li) print(list(ret)) # 输出 [33,44,55,66] # 通过lambda表达式来实现相同的功能 li = [11,22,33,44,55] result = filter(lambda a:a>33, li) print(list(result)) # 输出 [44,55] # map(函数,可迭代的对象) # li = [11,22,33,44,55] # def f1(args): # result = [] # for i in args: # result.append(100+i) # return result # r = f1(li) # print(list(r)) ## 输出 [111,122,133,144,155] def f2(a): return a + 100 result = map(f2, li) print(list(result)) # 输出 [111,122,133,144,155] # 通过lambda表达式替代简单的函数 result = map(lambda a: a+100, li) print(list(result)) # 输出 [111,122,133,144,155] # 总结: # filter:函数返回True,将元素添加到结果中 # map:将函数返回值添加到结果中 --------------------------------------------------- #frozenset 不可变的集合 --------------------------------------------------- # globals 代表所有的全局变量 # locals 代表所有的局部变量 # 例: NAME = "bourbon" def show(): a = 123 print(locals()) print(globals()) show() --------------------------------------------------- # hash()哈希值 python内部存储通过哈希值做索引 # id() 查看内存地址 --------------------------------------------------- # len()计算长度 # python 3 默认按照字符的方式查看 # python 2 只能以字节的方式查看 s = "田思寒" print(len(s)) # 输出 3 s = "田思寒" b = bytes(s, encoding='utf-8') print(len(b)) # 输出 9 ---------------------------------------------------- # max() 求最大值 # min() 求最小值 # sum() 求和 ----------------------------------------------------- # pow() 求指数 # 2的10次方 2**10 或 r = pow(2 , 10) print(r) ---------------------------------------------------- # reversed() 翻转 # round() 四舍五入 ---------------------------------------------------- # slice()切片的功能,一般不用 ---------------------------------------------------- li = [11,2,1,1] li.sort() sorted(li) #排序 ---------------------------------------------------- l1 = ["Hello",11,22,33] l2 = ["my",11,22,33] l3 = ["world",11,22,33] r = zip(l1,l2,l3) temp = list(r)[0] ret = ' '.join(temp) print(ret) zip 函数接受任意多个(包括0个和1个)序列作为参数 ----------------------------------------------------
文件操作
对文件操作流程:
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
文件句柄 = open('文件路径', '模式')
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
- r,只读模式(默认)
- w,只写模式(不可读)不存在则创建;存在则删除内容
- a,追加模式(不可读)不存在则创建;存在则只追加内容
- x,创建并写(不可读)如果文件已存在则报错
"+" 表示可以同时读写某个文件
- r+, 读写【可读,可写】
- w+,写读【可读,可写】
- x+ ,写读【可读,可写】
- a+, 写读【可读,可写】
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示以字节的方式操作
- rb 或 r+b
- wb 或 w+b
- xb 或 w+b
- ab 或 a+b
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型
操作:
#for循环文件对象 f = open("db","r",encoding="utf-8") for line in f: print(line)
2.6版本之后支持with 打开多个文件:
# 同时打开两个文件 with open('db1','r',encoding="utf-8")as f1,open('db2','w',encoding="utf-8") as f2: # 设置一个计数器 times = 0 for line in f1: times += 1 # 将db1中的文件逐行插入到db2中 if times <= 10: f2.write(line) # 如果计数器大于10则退出 else: break
逐行查找替换:
with open('db1','r',encoding="utf-8")as f1,open('db2','w',encoding="utf-8") as f2: for line in f1: new_str = line.replace("sheldon","bourbon") f2.write(new_str)
class file(object) def close(self): # real signature unknown; restored from __doc__ 关闭文件 """ close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to True. A closed file cannot be used for further I/O operations. close() may be called more than once without error. Some kinds of file objects (for example, opened by popen()) may return an exit status upon closing. """ def fileno(self): # real signature unknown; restored from __doc__ 文件描述符 """ fileno() -> integer "file descriptor". This is needed for lower-level file interfaces, such os.read(). """ return 0 def flush(self): # real signature unknown; restored from __doc__ 刷新文件内部缓冲区 """ flush() -> None. Flush the internal I/O buffer. """ pass def isatty(self): # real signature unknown; restored from __doc__ 判断文件是否是同意tty设备 """ isatty() -> true or false. True if the file is connected to a tty device. """ return False def next(self): # real signature unknown; restored from __doc__ 获取下一行数据,不存在,则报错 """ x.next() -> the next value, or raise StopIteration """ pass def read(self, size=None): # real signature unknown; restored from __doc__ 读取指定字节数据 """ read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. """ pass def readinto(self): # real signature unknown; restored from __doc__ 读取到缓冲区,不要用,将被遗弃 """ readinto() -> Undocumented. Don't use this; it may go away. """ pass def readline(self, size=None): # real signature unknown; restored from __doc__ 仅读取一行数据 """ readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF. """ pass def readlines(self, size=None): # real signature unknown; restored from __doc__ 读取所有数据,并根据换行保存值列表 """ readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read. The optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned. """ return [] def seek(self, offset, whence=None): # real signature unknown; restored from __doc__ 指定文件中指针位置 """ seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to (offset from start of file, offset should be >= 0); other values are 1 (move relative to current position, positive or negative), and 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). If the file is opened in text mode, only offsets returned by tell() are legal. Use of other offsets causes undefined behavior. Note that not all file objects are seekable. """ pass def tell(self): # real signature unknown; restored from __doc__ 获取当前指针位置 """ tell() -> current file position, an integer (may be a long integer). """ pass def truncate(self, size=None): # real signature unknown; restored from __doc__ 截断数据,仅保留指定之前数据 """ truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell(). """ pass def write(self, p_str): # real signature unknown; restored from __doc__ 写内容 """ write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written. """ pass def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__ 将一个字符串列表写入文件 """ writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object producing strings. This is equivalent to calling write() for each string. """ pass def xreadlines(self): # real signature unknown; restored from __doc__ 可用于逐行读取文件,非全部 """ xreadlines() -> returns self. For backward compatibility. File objects now include the performance optimizations previously implemented in the xreadlines module. """ pass
class TextIOWrapper(_TextIOBase): """ Character and line based layer over a BufferedIOBase object, buffer. encoding gives the name of the encoding that the stream will be decoded or encoded with. It defaults to locale.getpreferredencoding(False). errors determines the strictness of encoding and decoding (see help(codecs.Codec) or the documentation for codecs.register) and defaults to "strict". newline controls how line endings are handled. It can be None, '', '\n', '\r', and '\r\n'. It works as follows: * On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated. * On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string. If line_buffering is True, a call to flush is implied when a call to write contains a newline character. """ def close(self, *args, **kwargs): # real signature unknown 关闭文件 pass def fileno(self, *args, **kwargs): # real signature unknown 文件描述符 pass def flush(self, *args, **kwargs): # real signature unknown 刷新文件内部缓冲区 pass def isatty(self, *args, **kwargs): # real signature unknown 判断文件是否是同意tty设备 pass def read(self, *args, **kwargs): # real signature unknown 读取指定字节数据 pass def readable(self, *args, **kwargs): # real signature unknown 是否可读 pass def readline(self, *args, **kwargs): # real signature unknown 仅读取一行数据 pass def seek(self, *args, **kwargs): # real signature unknown 指定文件中指针位置 pass def seekable(self, *args, **kwargs): # real signature unknown 指针是否可操作 pass def tell(self, *args, **kwargs): # real signature unknown 获取指针位置 pass def truncate(self, *args, **kwargs): # real signature unknown 截断数据,仅保留指定之前数据 pass def writable(self, *args, **kwargs): # real signature unknown 是否可写 pass def write(self, *args, **kwargs): # real signature unknown 写内容 pass def __getstate__(self, *args, **kwargs): # real signature unknown pass def __init__(self, *args, **kwargs): # real signature unknown pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __next__(self, *args, **kwargs): # real signature unknown """ Implement next(self). """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
三元运算
三元运算(三目运算),是对简单的条件语句的缩写。
# 三元运算,三日运算,if...else...的简写 # 书写格式 result = 值1 if 条件 else 值2 # 如果条件成立,那么将 “值1” 赋值给result变量,否则,将“值2”赋值给result变量 if 1 == 1: name = "bourbon" else: name = "jerry" # 如果中间的if条件成立,name 则等于 bourbon,否则name等于jerry name = "bourbon" if 1 == 1 else "jerry"
lambda表达式
python 使用 lambda 来创建匿名函数。
- lambda只是一个表达式,函数体比def简单很多。
- lambda的主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。
- lambda函数拥有自己的命名空间,且不能访问自有参数列表之外或全局命名空间里的参数。
- 虽然lambda函数看起来只能写一行,却不等同于C或C++的内联函数,后者的目的是调用小函数时不占用栈内存从而增加运行效率。
语法
lambda函数的语法只包含一个语句,如下:
lambda [arg1 [,arg2,.....argn]]:expression
如下实例:
######################简单的函数###################### def f1(a1): return a1 + 100 ret = f1(10) print(ret) # 输出 110 ######################lambda表达式###################### # lambda的表达式只能写一行,只能对简单的赋值做操作 f2 = lambda a1,a2:a1+100+a2 r2 = f2(9,19) print(r2) # 输出 128