python 课堂 6 内置函数

查看全部内置函数:

print(dir(__builtins__)):

['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', 

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

'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):
取绝对值
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.

s = 'for i in range(10):print(i)'
c = compile(s,'qianlei','exec')
print(c)
exec(c)

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

s = '''
def name():
    print('qianlei')
    return 'qianlei'
name()
'''

e = exec(s) #===》qianlei
print(e)    #===》None

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

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

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

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

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

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

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

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

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

s1 = set([1,2,3,4])
s2 = set([3,4,5,6])
print(s1 & s2)  # 交集
print(s1 | s2)  # 并集
print(s1 - s2)  # 差集
print(s2 - s1)  # 差集
print(s1 ^ s2)  # 对称差集

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

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

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

把元素和索引组成元组

e1 = enumerate(l,start=1)
for i,v in e1:
    print(i,v)
#   1 a
    2 b
    3 c
可以直接取出 索引和元素,还可以直接设置索引开始值。

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

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

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

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

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

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

s =slice(1,8,2) # slice(start,end,step)
l = [1,2,3,4,5,6,7,8,9,0,]
print(l[s])

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

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

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

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

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

def format():
格式化输出,

s1 = '{}是个帅哥,今年{},有很多{}'        # 按顺序传。
s2 = '{0}是个帅哥,今年{1},有很多{2}' # 指定顺序传。
s3 = '{name}是个帅哥,今年{age},有很多{money}'    # 指定名称传,关键字参数
d = '{name}是个帅哥,今年{age},有很多{money}'# 通过字典传,转换为关键字参数
l = '{0[0]}是个帅哥,今年{0[1]},有很多{0[2]}'#通过列表或元组,使用索引传入。
res1 = s1.format('钱磊',23,'钱')
res2 = s2.format('钱磊',23,'钱')
res3 = s3.format(name='钱磊',age=23,money='钱')
 # 字典前加** 转换为关键字参数。
res4 = d.format(**{'name':'钱磊','age':23,'money':'钱'})
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()
返回内存查看对象

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

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

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

猜你喜欢

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