python课堂6: 内置函数

查看全部内置函数:

print(dir(__builtins__)):

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‘]

计算:

def abs(*args, **kwargs): 
取绝对值

1 print(abs(-1)) 

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.

1 s = ‘for i in range(10):print(i)‘
2 c = compile(s,‘qianlei‘,‘exec‘)
3 print(c)
4 exec(c)

def exec(): 
执行字符串形式的代码,但是无返回值。

1 s = ‘‘‘
2 def name():
3 print(‘qianlei‘)
4 return ‘qianlei‘
5 name()
6 ‘‘‘
7
8 e = exec(s) #===》qianlei
9 print(e) #===》None

def eval() 
返回字符串形式的表达式的值。

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

版本,说明

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(): 用来构建类,和检测对象的类型。

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

class super(): 
解决多重继承的问题,用来调用父类的方法。 
def hasattr(): 
检测对象中是否含有相应属性 
def getattr(): 
获取对象中的属性 
def setattr(): 
设置对象属性 
def delattr(): 
删除对象中的属性

数据类型

class int() 
数字和字符串转化为整形 
class float() 
整数和字符串转化为浮点 
class str() 
将对象转化为适合人阅读的形式。 
class repr() 
将对象转化为适合解释器阅读的形式。 
class list() 
将对象转化为列表 
class tuple() 
将对象转化为元祖 
class dict(): 
创建字典

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)]) #可迭代对象

class set() 
将对象转化为集合

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) # 对称差集

class frozenset() 
不可变集合,内部元素不可修改,删除。

class enumerate(): 
返回枚举对象。

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

把元素和索引组成元组

1 e1 = enumerate(l,start=1)
2 for i,v in e1:
3 print(i,v)
4 # 1 a
5 2 b
6 3 c

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

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

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

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

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

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

class slice(): 
创建切片对象,用于直接切片

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])

class zip(): 
将不同可迭代对象中的元素打包成元组,组成zip对象,转换为列表或for循环可以查看。 
使用zip(*zip_obj)可以解压zip对象,还原为两个可迭代对象。

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)

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

def dir(): 
返回所有的属性,组成列表形式。

def exit(): 
退出程序 
def quit(): 
退出程序。

def format(): 
格式化输出,

 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,‘钱‘])

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() 
返回内存查看对象

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

def object(): 
所有类的基类 
def open(): 
打开文件,获取文件句柄,进行文件操作。 
def print(): 
打印内容到屏幕

class reversed(): 
反向排列可迭代对象,获得一个新的可迭代对象 
def sorted(): 
排列可迭代对象,数字按大小排,字符按ascii码表排。

原文地址:https://www.cnblogs.com/qianduoduo123/p/9256359.html

时间: 2024-08-02 07:42:31

python课堂6: 内置函数的相关文章

python中的内置函数getattr()

在python的官方文档中:getattr()的解释如下: getattr(object, name[, default]) Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For examp

python之路——内置函数与匿名函数

内置函数 python里的内置函数.截止到python版本3.6.2,现在python一共为我们提供了68个内置函数.它们就是python提供给你直接可以拿来使用的所有函数.这些函数有些我们已经用过了,有些我们还没用到过,还有一些是被封印了,必须等我们学了新知识才能解开封印的.那今天我们就一起来认识一下python的内置函数.这么多函数,我们该从何学起呢? 上面就是内置函数的表,68个函数都在这儿了.这个表的顺序是按照首字母的排列顺序来的,你会发现都混乱的堆在一起.比如,oct和bin和hex都

python学习交流 - 内置函数使用方法和应用举例

内置函数 python提供了68个内置函数,在使用过程中用户不再需要定义函数来实现内置函数支持的功能.更重要的是内置函数的算法是经过python作者优化的,并且部分是使用c语言实现,通常来说使用内置函数相比于用户自己定义函数实现相同功能,在执行效率和对内存的分配和使用上是要更加理想的.所以理解和熟练运用python中的内置函数,不仅可以增强代码的可读性,同时也可以提升代码的品质.下面对内置函数的使用方法进行分类介绍,以方便归纳理解. 一.查看作用域中变量相关 global () 功能:查看全局作

python之枚举--内置函数-enumerate()

python之枚举 内置函数 enumearate() enumerate()是python的内置函数 enumerate在字典上是枚举.列举的意思 对于一个可迭代的(iterable)/可遍历的对象(如列表.字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值 enumerate多用于在for循环中得到计数 enumerate()使用 如果对一个列表,既要遍历索引又要遍历元素时,首先可以这样写: list=["这","是","一个

Python标准库 内置函数print objects sep ' ' end '\n' file sys st

本函数是实现对象以字符串表示的方式格式化输出到流文件对象file里.其中所有非关键字参数都按str()方式进行转换为字符串输出,关键字参数sep是实现分隔符,比如多个参数输出时想要输出中间的分隔字符:关键字参数end是输出结束时的字符,默认是换行符\n:关键字参数file是定义流输出的文件,可以是标准的系统输出sys.stdout,也可以重定义为别的文件:参数flush是立即把内容输出到流文件,不作缓存. 例子: #print() print(1, 2, 3, sep = ',', end =

part2:Python 变量及简单类型,print 函数介绍,Python 关键字、内置函数介绍

Python是弱类型语言,关于弱类型有两个含义:(1).所有的变量无须声明即可使用,或者说对从末用过的变量赋值就是声明了该变量:(2).变量的数据类型可以随时改变,同一个变量可以进行多次赋值,可以赋数值型和字符串型值. 一. 单行注释和多行注释 注释可提高程序可读性,用于解释某行或某部分程序的作用和功能.此外注释也是调试程序的重要方式,在调试时可将不希望编译.执行的代码注释掉.注释还可以为别人或自己过一段时间后能读懂代码的目的提供帮助.合理的代码注释占源代码 1/3 左右. Python语言不能

python 关键字和内置函数

Python关键字(保留字)一览表 来自 http://c.biancheng.net/view/4188.html 保留字是 Python 语言中一些已经被赋予特定意义的单词,这就要求开发者在开发程序时,不能用这些保留字作为标识符给变量.函数.类.模板以及其他对象命名. 表 1 Python 保留字一览表 and as assert break class continue def del elif else except finally for from False global if im

Python经常使用内置函数介绍【filter,map,reduce,apply,zip】

Python是一门非常简洁,非常优雅的语言,其非常多内置函数结合起来使用,能够使用非常少的代码来实现非常多复杂的功能,假设相同的功能要让C/C++/Java来实现的话,可能会头大,事实上Python是将复杂的数据结构隐藏在内置函数中,用C语言来实现,所以仅仅要写出自己的业务逻辑Python会自己主动得出你想要的结果.这方面的内置函数主要有,filter,map,reduce,apply,结合匿名函数,列表解析一起使用,功能更加强大.使用内置函数最显而易见的优点是: 1. 速度快,使用内置函数,比

Python基础day-11[内置函数(未完),递归,匿名函数]

内置函数: abs() : 返回数字的绝对值.参数可以是整数或浮点数,如果参数是复数,则返回复数的模. print(abs(0.2)) print(abs(1)) print(abs(-4)) print(abs(-0.2)) print(abs(3+4j)) 执行结果: D:\Python\Python36-32\python.exe E:/Python/DAY-11/tmp.py 0.2 1 4 0.2 5.0 Process finished with exit code 0 all():