python license函数_python课堂7:内置函数

本文详细介绍了Python的内置函数,包括查看所有内置函数的方法、常用数学运算、数据类型转换、异常处理、字符串操作、面向对象特性等。重点讨论了`abs()`, `pow()`, `sum()`, `divmod()`, `round()`等函数的用法,并提供了实例演示。" 130775265,7825138,HuggingFace调用BERT词向量:环境配置与代码实践,"['深度学习', '自然语言处理', '模型应用', '代码调试', '开发环境']
摘要由CSDN通过智能技术生成

查看全部内置函数:

print(dir(__builtins__)):

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 'ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', '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',2

3 '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__',4

5 'abs', 'all', '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']

View Code

计算:

def abs(*args, **kwargs):

取绝对值

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 print(abs(-1))

View Code

def pow():

次方

def sum():

求和,参数传入列表元组

def divmod(x,y)

返回x//y,x%y。

def round():

round(float,num) 四舍五入,设置位数。

def max()

取对象最大值

def min()

取对象最小值

def bin()

返回整数的二进制形式

def oct()

返回整数的八进制形式

def hex()

返回整数的十六进制形式

class complex(object):

创建复数

检测

def all(*args, **kwargs):

可迭代对象中元素全部为True,则返回值为True.否则返回False,空列表返回True.

def any()

可迭代对象中元素全部为False,返回False ,否则返回值为True.空列表返回False.

def ascii()

字符在ascii 中返回可打印的字符串,不在ascii码中的返回unicode形式的二进制。

class bool(int)

返回对象的布尔值,空和0为False,其他为true

def breakpoint()

设置断点,用于程序的调试。

def callable()

检测是否可以被调用。被调用对象内部定义call()方法就可以被检测到。

def chr()

输入整数,返回对应的unicode编码表对应的字符。

def ord()

输入字符,返回对应的unicode编码表对应的序号。

编译,字符串形式代码的运行

def compile():

将字符串编译为字节码对象,用于运行,可以设定编译方法,eval或exec.

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 s = 'for i in range(10):print(i)'

2 c = compile(s,'qianlei','exec')3 print(c)4 exec(c)

View Code

def exec():

执行字符串形式的代码,但是无返回值。

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 s = '''

2 def name():3 print('qianlei')4 return 'qianlei'5 name()6 '''

7

8 e = exec(s) #===》qianlei

9 print(e) #===》None

View Code

def eval()

返回字符串形式的表达式的值。

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 res = eval('3+2')2 print(res)

View Code

版本,说明

def copyright()

interactive prompt objects for printing the license text, a list of

contributors and the copyright notice.

def credits()

interactive prompt objects for printing the license text, a list of

contributors and the copyright notice.

def license()

interactive prompt objects for printing the license text, a list of

contributors and the copyright notice.

面向对象

class classmethod() : 类方法,直接使用类名调用的方法,使用对象也可以调用,装饰器定义类方法,参数中需要传入cls。

class staticmethod():静态方法,不属于类或对象,静态方法就是类中的工具集。

class property() :类中定义属性方法,方法可以当做属性来调用。

class type(): 用来构建类,和检测对象的类型。

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 Class_test = type('A',(object,),{'a':1,'b':2})2 c =Class_test()3 print(c.b)4

5 print(type('test'))

View Code

class super():

解决多重继承的问题,用来调用父类的方法。

def hasattr():

检测对象中是否含有相应属性

def getattr():

获取对象中的属性

def setattr():

设置对象属性

def delattr():

删除对象中的属性

数据类型

class int()

数字和字符串转化为整形

class float()

整数和字符串转化为浮点

class str()

将对象转化为适合人阅读的形式。

class repr()

将对象转化为适合解释器阅读的形式。

class list()

将对象转化为列表

class tuple()

将对象转化为元祖

class dict():

创建字典

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 d = dict(a=1213,v=232) #关键字

2

3 d = dict(**{'a':123,"b":232}) #字典

4

5 d = dict(zip(['a','v','c'],[1,2,3])) #映射函数

6

7 d = dict([('a',1),('b',2),('c',3)]) #可迭代对象

View Code

class set()

将对象转化为集合

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 s1 = set([1,2,3,4])2 s2 = set([3,4,5,6])3 print(s1 & s2) #交集

4 print(s1 | s2) #并集

5 print(s1 - s2) #差集

6 print(s2 - s1) #差集

7 print(s1 ^ s2) #对称差集

View Code

class frozenset()

不可变集合,内部元素不可修改,删除。

class enumerate():

返回枚举对象。

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 l = ['a','b','c']2 e =enumerate(l)3 print(list(e))4 #[(0, 'a'), (1, 'b'), (2, 'c')]

View Code

把元素和索引组成元组

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 e1 = enumerate(l,start=1)2 for i,v ine1:3 print(i,v)4 #1 a

5 2b6 3 c

View Code

可以直接取出 索引和元素,还可以直接设置索引开始值。

class map()

换入函数和可迭代对象,根据函数要求返回映射结果。

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 m = map(lambda x:x%2 ,list(range(10)))2 print(m)3 print(list(m))

View Code

class filter()

传入函数和可迭代对象,返回符合函数要求的可迭代对象的元素。

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 f = filter(lambda x:x%2==1 , list(range(500)))2 print(f)3 print(list(f))

View Code

class range()

创建一个数字范围对象,range(start,end,step)

class slice():

创建切片对象,用于直接切片

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 s =slice(1,8,2) #slice(start,end,step)

2 l = [1,2,3,4,5,6,7,8,9,0,]3 print(l[s])

View Code

class zip():

将不同可迭代对象中的元素打包成元组,组成zip对象,转换为列表或for循环可以查看。

使用zip(*zip_obj)可以解压zip对象,还原为两个可迭代对象。

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 l1 = [1,2,3]2 l2 = [4,5,6]3 l3 = [7,8,9,0]4 z1 =zip(l1,l2)5 print(list(z1)6 print(list(zip(l1,l3)))7 a,b = zip(*z1)8 print(a)9 print(b)

View Code

class bytearray()

返回对应数据的字节数组,如果是字符串必须指定编码。(可以修改字节内容)

class bytes()

返回对应数据的二进制形式,如果是字符串必须指定编码。(不可以修改内容)

def dir():

返回所有的属性,组成列表形式。

def exit():

退出程序

def quit():

退出程序。

def format():

格式化输出,

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 s1 = '{}是个帅哥,今年{},有很多{}' #按顺序传。

2 s2 = '{0}是个帅哥,今年{1},有很多{2}' #指定顺序传。

3 s3 = '{name}是个帅哥,今年{age},有很多{money}' #指定名称传,关键字参数

4 d = '{name}是个帅哥,今年{age},有很多{money}'#通过字典传,转换为关键字参数

5 l = '{0[0]}是个帅哥,今年{0[1]},有很多{0[2]}'#通过列表或元组,使用索引传入。

6 res1 = s1.format('钱磊',23,'钱')7 res2 = s2.format('钱磊',23,'钱')8 res3 = s3.format(name='钱磊',age=23,money='钱')9 #字典前加** 转换为关键字参数。

10 res4 = d.format(**{'name':'钱磊','age':23,'money':'钱'})11 res5 = l.format(['钱磊',23,'钱'])

View Code

def globals():

以字典的形式返回当前全部的全局变量。

def locals():

以字典形式返回当前全部的局部变量。

def vars()

vars(obj) 返回对象的属性字典。

def hash():

返回对象的hash值,字符串 数字 布尔 等不可变对象才可以哈希,列表字典等不可以哈希。

def help():

查看模块或函数详细的帮助信息。

def id():

返回对象内存地址。

def input:

用户交互,返回用户输入的信息,参数传入提示信息。

res = input('输入您的姓名:')

def isinstance():

检测对象是否为对应的类型

print(2,int)

def issubclass():

检测类是否为对应的子类

def iter():

转变可迭代类型为迭代器。

i=iter([1,2,3,4])

i1 = [1,2,3,4].iter()

迭代器每次只读取下一个元素进入内存,所以节省内存。

iter(iterable) == iterable.iter()

调用时使用 next(iter) == iter.next()

def next():

取出迭代器中的元素,和next() 相同。

def len()

返回对象长度,个数。

def memoryview()

返回内存查看对象

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 m = memoryview(bytes('qianlei'.encode('utf8')))2 print(m)

View Code

def object():

所有类的基类

def open():

打开文件,获取文件句柄,进行文件操作。

def print():

打印内容到屏幕

class reversed():

反向排列可迭代对象,获得一个新的可迭代对象

def sorted():

排列可迭代对象,数字按大小排,字符按ascii码表排。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值