回顾一下在之前文章中了解过的内置函数
dir(object):主要用于查看对象的所有属性和方法,能够帮助使用者多加了解对象的功能。
dir()
如果不传入参数的话,它会返回当前本地作用域中的名称列表(当先作用域中定义的变量、函数、类等名称)【列表顺序仅仅按照首字母的ASCII顺序打印,与使用频率重要性无关】def show():
pass
num = 10
circle = 3.14
print(dir())
"""
['__annotations__', '__builtins__', '__cached__',
'__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__',
'circle', 'num', 'show']
"""
dir(object)
传入一个对象作为参数时,它会返回该对象的所有属性和方法的名称-列表形式。arr = [1,2,3,4]
s = {1,2,3,4}
print(dir(arr))
print(dir(s))
"""
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
['__and__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
"""
# 查看所有Python的内置函数/内置数据
count = 0
for item in dir(__builtins__):
print(item, end = "\t")
count += 1
if count % 10 == 0:
print()
"""
ArithmeticError AssertionError AttributeError BaseException BaseExceptionGroup BlockingIOError BrokenPipeError BufferError BytesWarning ChildProcessError
ConnectionAbortedError ConnectionError ConnectionRefusedError ConnectionResetError DeprecationWarning EOFError Ellipsis EncodingWarning EnvironmentError Exception
ExceptionGroup False FileExistsError FileNotFoundError FloatingPointError FutureWarning GeneratorExit IOError ImportError ImportWarning
IndentationError IndexError InterruptedError IsADirectoryError KeyError KeyboardInterrupt LookupError MemoryError ModuleNotFoundError NameError
None NotADirectoryError NotImplemented NotImplementedError OSError OverflowError PendingDeprecationWarning PermissionError ProcessLookupError RecursionError
ReferenceError ResourceWarning RuntimeError RuntimeWarning StopAsyncIteration StopIteration SyntaxError SyntaxWarning SystemError SystemExit
TabError TimeoutError True TypeError UnboundLocalError UnicodeDecodeError UnicodeEncodeError UnicodeError UnicodeTranslateError UnicodeWarning
UserWarning ValueError Warning WindowsError ZeroDivisionError __build_class__ __debug__ __doc__ __import__ __loader__
__name__ __package__ __spec__ abs aiter all anext any ascii bin
bool breakpoint bytearray bytes callable chr classmethod compile complex copyright
credits delattr dict dir divmod enumerate eval exec exit filter
float format frozenset getattr globals hasattr hash help hex id
input int isinstance issubclass iter len license list locals map
max memoryview min next object oct open ord pow print
property quit range repr reversed round set setattr slice sorted
staticmethod str sum super tuple type vars zip
"""
round(number, ndigits):用于对数字进行四舍五入操作
number
:必须要填写的内容,对哪个数字进行四舍五入,可以是整数也可以是小数ndigits
:可选参数,是一个整数,用来指定要保留的小数位数,如果不写则默认为0print(round(5))
print(round(3.2))
print(round(3.8))
print(round(3.1415926, 3))
额外的,对于处理结尾为5的数字时,采用的是“银行家舍入法”,会将其舍入到最接近的偶数。
print(round(2.5)) # 2
print(round(3.5)) # 4
print(round(4.5)) # 4
print(round(5.5)) # 6
ndigits
也可以是负数,将整数部分进行四舍五入
print(round(12345, -3)) # 12000
all(iterable):用于判断可迭代对象中的所有元素是否都为真
iterable
:必填,可迭代对象(列表、字符串、元组、集合、字典)
什么是假:False、0、0.0、“”、[]、{}、()、None
arr = [1, 3.14, [1,2,3],{1,2,3}]
print(all(arr)) # True
arr = [1, 3.14, [],{1,2,3}]
print(all(arr)) # False
# 针对字典的操作 主要看键 不管值
dic = {"name":"张三","age":18, 0:666}
print(all(dic)) # False
any(iterable):用于判断可迭代对象中是都至少包含一个元素为真
filter(function, iterable):用于过滤可迭代对象中的元素,返回的是一个迭代器
function
:用于筛选元素的函数,必须返回一个布尔类型的值arr = [1,2,3,4,5,6,7,8,9,10]
arr1 = [item for item in arr if item % 2 == 0]
print(arr1)
# 过滤函数对某一个元素进行具体的操作
def is_even(number):
return number % 2 == 0
arr2 = list(filter(is_even, arr))
print(arr2)
如果不传入过滤函数时(传入None参数),则自动默认将可迭代对象中的假值进行过滤。
arr = [0,0.0,[],"",1,2,3]
lst = list(filter(None,arr))
print(lst)
next(Iterator, default):主要用于获取迭代器的下一个元素。
Iterator
:迭代器(实现了__next__
方法的对象)default
:可选参数,当迭代器耗尽时,既没有更多元素时,返回这个默认值(结束标记),如果不写则遍历结束时会报错。arr = [1,2,3,4,5,6,7,8,9,10]
def is_even(number):
return number % 2 == 0
it = filter(is_even, arr)
print(next(it)) # 2 每调用一次next 生成一个元素
print(next(it)) # 4
arr = [1,2,3,4]
# 获取可迭代对象的迭代器
it = iter(arr)
print(it)
print(type(it))
print(next(it))
print(next(it))
print(next(it))
print(next(it))
print(next(it)) # 此时it工作已经结束了 不能再被复用
"""
1
2
3
4
Traceback (most recent call last):
File "C:\Users\HENG\Desktop\PyDay20\Demo.py", line 10, in
print(next(it))
^^^^^^^^
StopIteration
"""
arr = [1,2,3,4]
# 获取可迭代对象的迭代器
it = iter(arr)
while True:
num = next(it, -1)
if num == -1:
break
print(num)
dic = {0:1,1:2,2:3,3:4,4:5}
it = iter(dic.keys())
print(next(it))
print(next(it))
iter(iterable) / iter(callable, sentinel)
iter(iterable)
:获取某一个可迭代对象的迭代器arr = [1,2,3,4]
# 获取可迭代对象的迭代器
it = iter(arr)
while True:
num = next(it, -1)
if num == -1:
break
print(num)
arr = [1,2,3,4]
# 获取可迭代对象的迭代器
it = iter(arr)
for number in it:
print(number)
iter(callable, sentinel)
:可以自定义一个迭代函数callable,来动态生成元素;sentinel标记值,当迭代到sentinel这个值时(返回值),则停止迭代。num = 1
def get_number():
global num # 全局
result = num # 局部
num += 1
return result
it = iter(get_number, 4)
for number in it:
print(number)
map(function, iterable,…):用于可迭代对象中的每一个元素应用指定的函数,并返回一个迭代器。
iterable,...
:可以传入多个可迭代对象的,对应的function也必须能够承接这么多的对象。def square(x):
return x ** 2
arr = [1,2,3,4]
it = map(square, arr)
for num in it:
print(num)
def square(x, y):
return x + y
arr1 = [1,2,3,4]
arr2 = [5,6,7,8]
it = map(square, arr1, arr2)
for num in it:
print(num)
reversed(seq):用于返回一个反向迭代器,逆序遍历,不对原数据做改变
seq
:必填参数,代表一个序列。arr = [1,2,3,4,5]
# 反向的迭代器
it = reversed(arr)
for num in it:
print(num)
zip(*iterables):用于将多个可迭代对象中对应位置的元素打包成一个个元组,然后返回这些元组组成的迭代器。以最短为主。
arr1 = [1,2,3,4,5]
arr2 = ['A','B','C','D','E']
arr3 = ['a','b','c','d','e']
it = zip(arr1, arr2, arr3)
for item in it:
print(item)
arr1 = [1,2,3,4,5]
arr2 = ['A','B','C','D','E']
arr3 = ['a','b','c','d','e']
it = zip(arr1, arr2, arr3)
for item in it:
print(item)
it = zip(arr1, arr2, arr3)
for a,b,c in it:
print(a,b,c)
可以使用*
对zip函数的结果进行解压缩,结果还是元组对象。
paris = [
(1, 'A', 'a'),
(2, 'B', 'b'),
(3, 'C', 'c'),
(4, 'D', 'd'),
(5, 'E', 'e')
]
print(paris)
lst1, lst2, lst3 = zip(*paris)
print(lst1)
print(lst2)
print(lst3)
以下是更多内置函数,在此不赘述,感兴趣的可以自己了解
函数 | 说明 |
---|---|
aiter() | 从异步对象中获取对应的异步迭代器 |
anext() | 从异步迭代器中获取下一个数据 |
ascii() | 判断参数数据是否一个标准的可打印ascii字符 |
breakpoint() | 间接调用系统中的钩子函数进行代码调试 |
bytearray() | Python中用来创建字节数组的函数 |
bytes() | 构建字节序列的,类似bytearray、 |
callable() | 判断参数数据是否可以被执行,经常用于编写后门木马时探测目标数据 |
classmethod | 面向对象中-用于声明类方法的装饰器函数 |
compile() | 用于将字符串数据编译成可执行脚本,提供给exec()或者eval()函数调用执行 |
complex() | 数据处理中用于复数处理的类型 |
copyright() | python内置的 版本信息 内置函数 |
credits() | python内置的 贡献者信息 内置函数 |
delattr() | 面向对象中-用于删除对象属性的函数 |
divmod() | 用于直接查询整除数据和取余数据的函数 |
exec() | 类似eval(),也可以将字符串转化成表达式进行执行 |
format() | 用于数据格式化的函数 |
frozenset() | 用于将序列数据进行乱序处理的函数 |
getattr() | 面向对象中-用于获取对象中的属性的函数 |
globals() | 用于获取当前作用域中所有全局变量的函数 |
locals() | 用于获取当前作用域中所有局部变量的函数,类似vars() |
vars() | 用于获取当前作用域中所有局部变量的函数,类似vars() |
hasattr() | 面向对象中-用于判断对象中是否包含某个属性的函数 |
hash() | 用于获取参数数据的hash值的函数,底层函数 |
isinstance() | 面向对象中-身份运算符,判断某个对象是否属于某种类型,如张三是个人吗? |
issubclass() | 面向对象中-身份运算符,判断某个小类型是否属于某个大类型,如男人是人吗? |
license() | python中的版本信息 |
memoryview() | 用于获取参数数据的内存数据 |
object() | python中的顶级对象类型 |
open() | 内置的用于打开并操作系统文件的函数 |
property() | 面向对象-用于对象属性封装 |
repr() | 面向对象-用于输出对象 |
setattr() | 面向对象-用于给对象设置属性的函数 |
slice() | 用于阶段拆分字符串的内置函数 |
staticmethod() | 面向对象-用于声明静态方法的装饰器函数 |
super() | 面向对象-用于表示继承关系中父类型的关键字 |
什么是模块
.py
文件就是一个模块。创建模块
# my_math.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
# 抛出异常
raise ValueError("除数不能为零")
return a / b
导入模块
(1)在另一个Python文件中,直接导入模块
import 模块名称
# main.py
import my_math
print(my_math.add(1,3))
print(my_math.subtract(3,1))
使用别名导入(就是给模块另起名字,一旦使用别名,本身的名称就不可用)
import 模块名称 as 别名
# main.py
import my_math as mm
print(mm.add(1,3))
print(mm.subtract(3,1))
(2)直接从模块中导入需要的对象(函数、变量、类)
from 模块 import 对象,对象...
# main.py
from my_math import add, subtract,multiply,divide
print(add(1,3))
print(subtract(4,1))
好处就是可以不用通过模块名称来去调用
坏处:
# main.py
from my_math import add, subtract,multiply,divide
def add(a,b):
return 666
print(add(1,3))
print(subtract(4,1))
(3)导入模块所有的对象
from 模块 import *
# main.py
from my_math import *
print(add(1,3))
print(subtract(4,1))
模块中__name__
的属性
__name__
。当模块被直接运行时,__name__
的值为__main__
;当模块被导入时,__name__
的值为模块名称。# my_math.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
# 抛出异常
raise ValueError("除数不能为零")
return a / b
# print(__name__)
# 当直接执行my_math.py文件时 则执行下面if中的内容
# 当my_math.py被导入时,则下面if中的内容不执行
if __name__ == "__main__":
print(f"测试:{add(1,1)}")
print(f"测试:{subtract(1,1)}")
什么是包
包是一种管理Python模块的方式,它实际上就是一个包含多个模块的目录。包目录下必须有一个__init__.py
的文件,该文件就是用来标记当前目录是一个普通文件夹还是一个包。
在大型项目开发中,代码功能其实可以分为这么几类:model、view、controller、DB
创建包
创建一个名为my_package
的包,目录结构:
my_package
__init__.py
ModelC.py
ModelD.py
# ModelC.py
def show_modelC():
print("show_modelC run...")
# ModelD.py
def show_modelD():
print("show_modelD run...")
导入包中的模块
(1)相对导入
在包内,模块之间进行相互导入。【导包时,严禁相关导入,否则出现递归异常】
# ModelD.py
from . import ModelC
def show_modelD():
print("show_modelD run...")
ModelC.show_modelC()
(2)绝对导入
在包外,其他的模块中进行导入
# main.py
from my_package import ModelC, ModelD
ModelC.show_modelC()
ModelD.show_modelD()
__init__
的作用
# __init__.py
from . import ModelC
from . import ModelD
# main.py
import my_package
my_package.ModelC.show_modelC()
my_package.ModelD.show_modelD()
__init__
中的__all__
变量
它是一个字符串列表,指定当前使用 from 包 import *
时应该导入的模块,做记录/指定导入。
# main.py
from my_package import *
ModelC.show_modelC()
ModelD.show_modelD()
print(dir())
# __init__.py
__all__ = ["ModelC", "ModelD"]