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']
View Code

计算:

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

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.

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(): 
执行字符串形式的代码,但是无返回值。

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() 
返回字符串形式的表达式的值。

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

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(): 
创建字典

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() 
将对象转化为集合

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(): 
返回枚举对象。

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

把元素和索引组成元组

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
View Code
可以直接取出 索引和元素,还可以直接设置索引开始值。

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

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

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

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(): 
创建切片对象,用于直接切片

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对象,还原为两个可迭代对象。

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(): 
格式化输出,

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

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

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

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

猜你喜欢

转载自www.cnblogs.com/qianduoduo123/p/9256359.html