本課主題
- 內置函数介紹和操作实战
- 装饰器介紹和操作实战
- 本周作业
內置函数介紹和操作实战
返回Boolean值的內置函数
- all( ): 接受一個可以被迭代的對象,如果函数裡所有為真,才會真;有一個是假就會返回假‧
all( )函数例子>>> a1 = all([1,2,3,4]) >>> print(a1) True >>> a2 = all([1,2,3,0]) >>> print(a2) False >>> a3 = all([1,2,3,[]]) >>> print(a3) False
- any( ): 接受一個可以被迭代的對象,如果函数裡只要有真,就會真;所有為假才會返回假‧
any( )函数例子>>> n1 = any([1,2,3,4]) >>> print(n1) True >>> n2 = any([1,2,3,0]) >>> print(n2) True >>> n3 = any([1,2,3,[]]) >>> print(n3) True >>> n4 = any([0,(),{},[]]) >>> print(n4) False
- bool( ): 判断什麼時候是真,什麼時候是假
bool( )函数例子>>> print(bool(0)) False >>> print(bool(None)) False >>> print(bool("")) False >>> print(bool([])) False >>> print(bool({})) False >>> print(bool(())) False >>> print(bool(" ")) True >>> print(bool(1)) True >>> print(bool(-1)) True
面向对象相关的内置函数
- ascii( ): 它會自动执行对象里的 __repr___方法,然後取 __repr___方法裡的值。
ascii( )函数例子>>> class Foo: ... def __repr__(self): ... return "111" ... >>> n = ascii(Foo()) #自动执行对象里的 __repr___方法 >>> print(n)
- staticmethod( ):
- repr( ):
repr( )函数例子>>> class Foo: ... def __repr__(self): ... return "111" ... >>> n = repr(Foo()) #自动执行对象里的 __repr___方法 >>> print(n)
- object( ):
- property( ):
- isinstance( ): 判断某一个对象是谁的实例,对象和类是什么关系,对于 str 这个类可以创建,执行功能的时候,都会到 str 里找,对象跟类是有关系的。另外一种说法是对象是类的实例,

isinstance( )函数例子s = "alex" r1 = isinstance(s, str) #判断对象是否是 str 的事例 print(r1) #True r2 = isinstance(s, dict) #判断对象是否是 dict 的事例 print(r2) #False r3 = isinstance(s, list) #判断对象是否是 list 的事例 print(r3) #False
- super( ):
返回数字的内置函数
- round( ):四写五入传进来的数字
- abs( ): 取绝对值
abs( )例子>>> n = abs(-1) >>> print(n) 1
- divmod( ):计算余数
divmod( )函数例子>>> r = divmod(97,10) # 會返回 Tuple >>> print(r) (9, 7) >>> print(r[0]) >>> print(r[1]) #余數 >>> (n1,n2) = divmod(97,10) # 會返回 Tuple >>> print(n1) >>> print(n2) #余數
- len( )
len( )函数例子#Python2 >>> s = "你好" >>> print(len(s)) #默认是按字节来判断长度 #Python3 >>> s = "你好" >>> print(len(s)) #默认是按字符来判断长度 >>> s = "你好" >>> s2 = bytes(s, encoding='utf-8') #Python3也可以按字节找 >>> print(len(s2))
- pow( )
pow( )函数例子>>> r1 = 2**10 >>> r2 = pow(2,10) >>> print(r1) 1024 >>> print(r2) 1024
- enumerate( )
enumerate( ) 例子>>> company = ["google", "facebook", "baidu", "alibaba", "yahoo", "IBM", "apple", "amazons"] >>> for com in enumerate(company): ... print(com) ... (0, 'google') (1, 'facebook') (2, 'baidu') (3, 'alibaba') (4, 'yahoo') (5, 'IBM') (6, 'apple') (7, 'amazons') >>> for com in enumerate(company, 10): ... print(com) ... (10, 'google') (11, 'facebook') (12, 'baidu') (13, 'alibaba') (14, 'yahoo') (15, 'IBM') (16, 'apple') (17, 'amazons')
字符、字节相关的内置函数
- bin( ): 这个函数接受一个十进制,然后转换成二进制
bin( )例子>>> print(bin(5)) 0b101
- oct( ): 这个函数接受一个十进制,然后转换成八进制
oct( )例子>>> print(oct(9)) 0o11
- hex( ): 这个函数接受一个十进制,然后转换成十六进制
hex( )例子>>> print(hex(15)) 0xf
- 字節
字节s = "李杰" #二进制:10101010 10101010 10101010 10101010 10101010 10101010 #十进制: 23 23 23 23 23 23 #十六进制: 2f 2g 2e 2d 2c 2f
如果想把一个字节串转换成字节类型需要调用 bytes( )函数,然后加上要转换的字符串,还有编码。如果想把字符串转换成字节类型,不同的编码会有不同大小的字节,它的二进制是表现形式
bytes( )例子>>> bytes("李杰",encoding='utf-8') b'\xe6\x9d\x8e\xe6\x9d\xb0' >>> bytes("李杰",encoding='gbk') b'\xc0\xee\xbd\xdc'
- 字节又怎么转换成字符串
str( )函数例子>>> n = bytes("李杰",encoding='utf-8') >>> n b'\xe6\x9d\x8e\xe6\x9d\xb0' >>> ret = str(n,encoding='utf-8') >>> print(ret) 李杰
- chr( ): 数字转换成字母
chr( )函数例子>>> r = chr(65) #把一个数节转换成字母 >>> print(r) #A A
- ord( ): 字母转换成数字
ord( )函数例子>>> n = ord("A") #把一个字母转换成数字 >>> print(n) #65 65
其他的内置函数
对于一个文件它保存是以0101010的方式保存,如果想操作文件,应该需要把它读取到内存里,Python 读取文章的内容到内存,内部会把一个字符串给你编译成一个特殊的代码,第三步才执行代码。 Compile( ) 就是用来编译代码
Compile( ) 和 exec( ):如果是 exec 的话,会给你编译Python 一样的代码,可以执行所有 Python 的东西。
>>> s = "print(123)" #这个字符串会放内存 >>> r = compile(s,"<string>","exec") >>> print(r) <code object <module> at 0x10345f810, file "<string>", line 1> >>> exec(r) 123
如果是 single 的话,会给你编译成单行的 Python 程序
如果是 eval 的话,会给你编译成表达式,拿到一个字符串,变成了表达式然后去执行它,eval 是有返回值的,它会执行程序并可以把结果返回给另外一个参数。
s2 = "8*8" ret = eval(s2) print(ret) #64
dir( ): 快速获取一下一个类提供了哪些功能
>>> print(dir(dict)) ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
help( ): 功能详细显示出来
>>> print(help(list)) class list(object) | list() -> new empty list | list(iterable) -> new list initialized from iterable's items | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return key in self. | | __delitem__(self, key, /) | Delete self[key]. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __gt__(self, value, /) | Return self>value. | | __iadd__(self, value, /) | Implement self+=value. | | __imul__(self, value, /) | Implement self*=value. | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __mul__(self, value, /) | Return self*value.n | | __ne__(self, value, /) | Return self!=value. | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | __repr__(self, /) | Return repr(self). | | __reversed__(...) | L.__reversed__() -- return a reverse iterator over the list | | __rmul__(self, value, /) | Return self*value. | | __setitem__(self, key, value, /) | Set self[key] to value. | | __sizeof__(...) | L.__sizeof__() -- size of L in memory, in bytes | | append(...) | L.append(object) -> None -- append object to end | | clear(...) | L.clear() -> None -- remove all items from L | | copy(...) | L.copy() -> list -- a shallow copy of L | | count(...) | L.count(value) -> integer -- return number of occurrences of value | | extend(...) | L.extend(iterable) -> None -- extend list by appending elements from the iterable | | index(...) | L.index(value, [start, [stop]]) -> integer -- return first index of value. | Raises ValueError if the value is not present. | | insert(...) | L.insert(index, object) -- insert object before index | | pop(...) | L.pop([index]) -> item -- remove and return item at index (default last). | Raises IndexError if list is empty or index is out of range. | | remove(...) | L.remove(value) -> None -- remove first occurrence of value. | Raises ValueError if the value is not present. | | reverse(...) | L.reverse() -- reverse *IN PLACE* | | sort(...) | L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None
filter( ): 函数返回 True,将元素添加到结果中,可以有兩個方法
- 先不用Python 的内置函数,都可以自己写一个有 filter 功能的函数
自定义有filter()功能的函数>>> def f1(args): ... results = [] ... for item in args: ... if item > 22: ... results.append(item) ... return results >>> li = [11,22,33,44,55,66,77,88,99] >>> ret = f1(li) >>> print(ret) [33, 44, 55, 66, 77, 88, 99]
- 然後現在的調用 Python 的內置函数:filter( ),filter(func,iter)
filter(func,iter) #func 接收一个函数 #iter 接收一个可迭代的对象
filter( )函数例子>>> def f2(a): ... if a > 22: ... return True ... >>> li = [11,22,33,44,55] >>> ret = filter(f2,li) #filter(func(),Iterator) >>> print(list(ret)) [33, 44, 55] # filter内部, 循环第二个参数 # results = [] # for item in 第二个参数: # r = 第一個参数(item) # if r: # results(item) # return results
- 调用 lambda 表达式也可以实现相同的功能
lambda表达式的filter( )函数例子#lambda 內部會幫自動 return # f1 = lambda a: a > 30 # ret = f1(90) li = [11,22,33,44,55] results = filter(lambda a: a > 33,li) print(list(results)) #[44, 55]
map( ):帮你遍历数组里的每一个元素,然后基于自己写的逻辑对数组进行处理。 map也会接收一个函数和一个可迭代的对象。
map(func,iter)
#func 接收一个函数
#iter 接收一个可迭代的对象
- 先不用Python 的内置函数,都可以自己写一个有 map 功能的函数
自定义有map()功能的函数>>> li = [11, 22, 33, 44, 55] >>> def f2(a): ... return a + 100 ... >>> results = map(f2,li) >>> print(list(results)) [111, 122, 133, 144, 155]
- 调用 lambda 表达式也可以实现相同的功能
lambda表达式的map( )函数例子li = [11, 22, 33, 44, 55] results = map(lambda a:a+100, li) print(list(results)) #[111, 122, 133, 144, 155]
在 Spark 裡用了很多 lamdba 表達式
from __future__ import print_function import sys from operator import add from pyspark.sql import SparkSession if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: wordcount <file>", file=sys.stderr) exit(-1) spark = SparkSession\ .builder\ .appName("PythonWordCount")\ .getOrCreate() lines = spark.read.text(sys.argv[1]).rdd.map(lambda r: r[0]) counts = lines.flatMap(lambda x: x.split(' ')) \ .map(lambda x: (x, 1)) \ .reduceByKey(add) output = counts.collect() for (word, count) in output: print("%s: %i" % (word, count)) spark.stop()
Zip( ):两个或以上的列表,各自列表的第 x个元素右起来组成新的元组
l1 = ["Python", 44, 11, 33, 22] l2 = ["is", 44, 11, 33, 22] l3 = ["Fun", 44, 11, 33, 22] r = zip(l1,l2,l3) temp = list(r)[0] ret = " ".join(temp) print(ret) #Python is Fun
locals( ): 代表所有的局部变量,都会放在这个函数里
global( ): 代表所有的全区变量,都会放在这个函数里
>>> NAME = "Janice" >>> def show(): ... a=123 ... >>> def show(): ... a=123 ... print(locals()) ... print(globals()) ... >>> show() {'a': 123} {'a3': False, 'add': <function <lambda> at 0x1034ab598>, 'n1': 9, 'r': (9, 7), 'li': [11, 22, 33, 44, 55], 'fruit': 'apple', '__package__': None, 'n3': True, 'results': <map object at 0x10376b668>, 'n4': False, '__name__': '__main__', 'NAME': 'Janice', 'Foo': <class '__main__.Foo'>, '__doc__': None, 'f1': <function f1 at 0x1034ab620>, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, 'f2': <function f2 at 0x1034ab510>, '__spec__': None, 'ret2': 110, '__builtins__': <module 'builtins' (built-in)>, 'name': 'apple', 'show': <function show at 0x10375c268>, 's': 'print(123)', 'n2': 7, 'a2': False, 'ret': <filter object at 0x10376b7f0>, 'a1': True, 'n': b'\xe6\x9d\x8e\xe6\x9d\xb0'}
hash( ): 生成一個hash值,它在內部經常用,一般用於字典的 Key 來保存
>>> s = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffff" #不会把整个字符串存储在内部里 >>> dic = {"ffffffffffffffffffffffffffffffffffffffffffffffffffffffff" : 1} #会首先把它转换成 hash 值然后以字典的 Key 方式存储在内部里 >>> hash("ffffffffffffffffffffffffffffffffffffffffffffffffffffffff") 7896373676960469870 >>> dic = {"7896373676960469870" : 1} >>> dic {'7896373676960469870': 1}
memoryview( ):
callable( ):
vars( ):
sorted( ): Python 有两个内置的排序函数,一种是调用 sorted(a) 函数但并不改变原来实例的顺序;另一种是调用 a.sort( )函数,这会改变原来目标的顺序
>>> a = [2, 4, 3, 5, 1] >>> sorted(a) [1, 2, 3, 4, 5] >>> a [2, 4, 3, 5, 1] >>> a.sort() >>> a [1, 2, 3, 4, 5]
装饰器的介紹和操作实战
单层装饰器
>>> def outer(): ... print("outer.....") ... >>> def f1(): ... outer() ... print("f1\n") ... >>> def f2(): ... outer() ... print("f2\n") ... >>> def f100(): ... outer() ... print("f100\n") ... >>> ff1 = f1() outer..... f1 >>> ff2 = f2() outer..... f2 >>> ff100 = f100() outer..... f100
- 开放封闭原则:对于类或者是函数的内部,对所有人来说是封闭的,你改函数的时候不要在函数内部改,意思是说如果需要统一修改或者是添加功能的话,不可以在类或者是函数的内部直接改,对类或者是函数的外部是开放的。不影响函数的执行下,在外部添加一个新功能
- 应用埸景:在不改变函数内容的前题下,在它的参数不变的基础上,在它的之前或者是之后统一的做一些操作为什么要使用装饰器,因为想在执行函数之前先做一些操作,然后在执行函数之后又做一些操作。我通过一些语法,在你执行函数之前做一些操作,之后又做一些操作。
装饰器例子[函数執行之前添加信息]>>> def outer(func): ... def inner(): ... print("log") ... return func() ... return inner ... >>> @outer #在函数的外部添加一个 outer 函数 ... def f1(): ... print("f1") ... >>> f1() log f1
装饰器例子[函数執行之后添加信息]>>> def outer(func): ... def inner(): ... print("decorator: before.....") ... r = func() ... print("decorator: after.....\n") ... return r ... return inner ... >>> @outer ... def f1(): ... print("f1") ... >>> ff1 = f1() decorator: before..... f1 decorator: after.....
- 对函数是一个整体来说是可以把它当参数传到另外一个函数里
函数当参数传到另外一个函数里def f1(): print(123) def f2(xxx): xxx() f2(f1) #123
函数是参数原理解析# 首先定义了 outer 函数 # 调用装饰器时会把f1这个整体当做参数传到 outer,然后把outer函数的返回再赋值给f1,这相当于 # def outer(): # return "123" # # f1 = "123" def outer(func): return "123" @outer def f1(): print("f1") f1 print(f1,type(f1)) #123 <class 'str'>
- 在你執行函数之前做一些操作,之後又做一些操作,装饰器有兩個主要的功能,
功能一、自动执行 outer 函数并且将下面的函数名 f1当作参数传
功能二、将 outer 函数的返回值返回,重新赋值给 f1
def outer(func): def inner(): print("before") func() #执行原来的函数 e.g. f1() print("after") return inner @outer def f1(): print("F1") - 也可以在原来的函数传入参数,当原函数有返回值时,在执行装饰器时也需要确保有返回值
装饰器例子[有一個参数]def outer(func): def inner(a): print("before") r = func(a) #执行原来的函数 e.g. f1() print("after") return r return inner # @ + 函数 然后放在一个函数上面 # 功能: #- 自动执行 outer 函数并且将下面的函数名 f1当作参数传 #- 将 outer 函数的返回值返回,重新赋值给 f1 @outer def f1(args): print(args) return ("返回了") @outer def f2(): print("F2")
装饰器例子[多个参数]def outer(func): def inner(*args, **kwargs): print("before") r = func(*args, **kwargs) #执行原来的函数 e.g. f1() print("after") return r return inner # @ + 函数 然后放在一个函数上面 # 功能: #- 自动执行 outer 函数并且将下面的函数名 f1当作参数传 #- 将 outer 函数的返回值返回,重新赋值给 f1 @outer def f1(args): print(args) return ("返回了") @outer def f2(arg1, arg2): print(arg1,arg2)
- 程序执行的步骤

import time def log_calls(func): def wrapper(*args, **kwargs): now = time.time() print("Calling {0} with {1} and {2}".format(func.__name__, args, kwargs)) return_value = func(*args, **kwargs) # call test1(1,2,3) function print("Executed {0} in {1}ms".format(func.__name__, time.time() - now)) return return_value return wrapper #log_calls(test1) @log_calls def test1(a,b,c): print("\ttest1 called") #log_calls(test2) @log_calls def test2(a,b): print("\ttest2 called") #log_calls(test3) @log_calls def test3(a,b): print("\ttest3 called") time.sleep(1) # test1 = log_calls(test1) # test2 = log_calls(test2) # test3 = log_calls(test3) test1(1,2,3) # wrapper(*args, **kwargs) test2(4,b=5) test3(6,7) """ Calling test1 with (1, 2, 3) and {} test1 called Executed test1 in 0.00011897087097167969ms Calling test2 with (4,) and {'b': 5} test2 called Executed test2 in 2.193450927734375e-05ms Calling test3 with (6, 7) and {} test3 called Executed test3 in 1.0049281120300293ms """
双层装饰器
[更新中]
案例实战
[更新中]
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Janice Cheng LOGIN_USER = {"is_login": False} def outer(func): def inner(*args, **kwargs): if LOGIN_USER["is_login"]: r = func() return r else: print("Please login First") return inner @outer def order(): print("Welcome {} ".format(LOGIN_USER["current_user"])) @outer def changepwd(): print("Welcome {} ".format(LOGIN_USER["current_user"])) @outer def manager(): print("Welcome {} ".format(LOGIN_USER["current_user"])) def login(user,pwd): if user == "janice" and pwd == "jc123456": LOGIN_USER["is_login"] = True LOGIN_USER["current_user"] = user print("login successful\n") def main(): while True: inp = input("1. 后台管理; 2.登录\n>> ") if inp == '1': manager() elif inp == '2': username = input("Username: ") password = input("password: ") login(username,password) main()
本周作业
优化用户管理程序
普通用户: 登录,注册,修改密码,查看本用户信息
管理员用户:登录,注册,修改密码,查看本用户信息
删除、添加普通用户
修改普通用户密码
查看所有普通用户,按照指定关键字搜索用户信息
提高用户权限
* 用户信息需要存储在文件:alex|123|alex@gmail.com|1
* 权限要用装饰器来实现
程序流程图

程序结果


参考资料
金角大王:
银角大王:Python开发【第四篇】:Python基础之函数
本文详细介绍了Python中的各种内置函数,如all(), any(), bool(), ascii(), repr(), isinstance(), round(), abs(), divmod(), len(), pow(), enumerate(), bin(), oct(), hex(), bytes(), str(), chr(), ord(), compile(), eval(), dir(), help(), filter(), map(), sorted(), hash(), memoryview(), callable(), vars()等,并通过实例展示了它们的使用方法。此外,还深入探讨了装饰器的概念及其实现方式,包括单层装饰器的应用场景和具体用法。
1270

被折叠的 条评论
为什么被折叠?



