师傅用时一个月!总结了68个内置函数的教程!零基础就该这么学!
一、内置函数 加群:960410445? ?即可获取数十套PDF! 语法:class complex([real[,imag]]) 参数: real -- int,long,float或字符串 imag -- int,float >>>complex(1,2) (1 + 2j) >>> complex(1) # 数字 (1 + 0j) >>> complex("1") # 当做字符串处理 (1 + 0j) # 注意:这个地方在"+"号两边不能有空格,也就是不能写成"1 + 2j",应该是"1+2j",否则会报错 >>> complex("1+2j") (1 + 2j) class bytearray([source[,encoding[,errors]]]) # 如果 source 为整数,则返回一个长度为 source 的初始化数组; # 如果 source 为字符串,则按照指定的 encoding 将字符串转换为字节序列; # 如果 source 为可迭代类型,则元素必须为[0,255] 中的整数; # 如果 source 为与 buffer 接口一致的对象,则此对象也可以被用于初始化 bytearray。 # 如果没有输入任何参数,默认就是初始化数组为0个元素。 >>>bytearray() bytearray(b'') >>> bytearray([1,2,3]) bytearray(b'x01x02x03') >>> bytearray('中文','utf-8') bytearray(b'xe4xb8xadxe6x96x87') (7) bytes()
>>> bytes('中文','utf-8') b'xe4xb8xadxe6x96x87' (11) bin()
>>>bin(10) '0b1010' >>> bin(20) '0b10100' (12) oct()
(13) hex()
(14) tuple()
>>> tuple() #不传入参数,创建空元组 () >>> tuple('121') #传入可迭代对象,使用其元素创建新的元组 ('1','2','1') (15) list()
>>>list() # 不传入参数,创建空列表 [] >>> list('abcd') # 传入可迭代对象,使用其元素创建新的列表 ['a','b','c','d'] (16) dict()
# 创建空字典 >>>dict() {} # 传入关键字 >>> dict(a='a',b='b',t='t') {'a': 'a','b': 'b','t': 't'} # 映射函数方式来构造字典 >>> dict(zip(['one','two','three'],[1,3])) {'three': 3,'two': 2,'one': 1} # 可迭代对象方式来构造字典 >>> dict([('one',1),('two',2),('three',3)]) {'three': 3,'one': 1} (17) set()
>>> a = set(range(10)) # 传入可迭代对象,创建集合 >>> a {0,1,3,4,5,6,7,8,9} >>> x = set('runoob') >>> y = set('google') >>> x,y (set(['b','r','u','o','n']),set(['e','g','l'])) # 重复的被删除 >>> x & y # 交集 set(['o']) >>> x | y # 并集 set(['b','e','l','n','u']) >>> x - y # 差集 set(['r','n']) (18) frozenset()
>>>a = frozenset(range(10)) # 生成一个新的不可变集合 >>> a frozenset([0,9]) >>> b = frozenset('runoob') >>> b frozenset(['b','n']) # 创建不可变集合 (19) enumerate()
>>>seasons = ['Spring','Summer','Fall','Winter'] >>>list(enumerate(seasons)) [(0,'Spring'),(1,'Summer'),(2,'Fall'),(3,'Winter')] # 指定起始值,小标从1开始 >>>list(enumerate(seasons,start=1)) [(1,(4,'Winter')] 普通for循环: >>>i = 0 >>>seq = ['one','three'] >>>for element in seq: ... print(i,seq[i]) ... i += 1 for循环使用enumerate >>>seq = ['one','three'] >>>for i,element in enumerate(seq): ... print(i,seq[i]) 同样输出: 0 one 1 two 2 three (20) range()
(21) iter()
>>> a = iter('abcd') #字符串序列 >>> a (22) slice()
语法: class slice(stop) class slice(start,stop[,step]) # 设置截取5个元素的切片 >>>myslice = slice(5) >>> myslice slice(None,None) >>> arr = range(10) >>> arr [0,9] # 截取 5 个元素 >>> arr[myslice] [0,4] (23) super()
语法:super(type[,object-or-type]) # type -- 类。 # object-or-type -- 类,一般是 self class A: pass class B(A): def add(self,x): super().add(x) (24) object()
3、序列操作(8个) (1) all()
>>> all(['a','','d']) # 列表list,存在一个为空的元素 False >>> all([0,1,2,3]) # 列表list,存在一个为0的元素 False >>> all([]) # 空列表 True >>> all(()) # 空元组 True (2) any()
(3) filter()
(4) map()
>>>def square(x) : # 计算平方数 ... return x ** 2 >>> map(square,5]) # 计算列表各个元素的平方 [1,9,16,25] >>> map(lambda x: x ** 2,5]) # 使用 lambda 匿名函数 [1,25]
(5) next()
>>> a = iter('abcd') >>> next(a) 'a' >>> next(a) 'b' >>> next(a) 'c' >>> next(a) 'd' >>> next(a) Traceback (most recent call last): File " (6) reversed()`` + 反转序列生成新的可迭代对象,语法: reversed(seq)` seqList = [1,5] print(list(reversed(seqList))) 输出: [5,1] (7) sorted()
语法:sorted(iterable,key=None,reverse=False) # key主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序,reverse=True降序,reverse=False升序(默认)。 >>>sorted({1: 'D',2: 'B',3: 'B',4: 'E',5: 'A'}) [1,5] # 利用key进行倒序排序 >>>example_list = [5,4] >>> result_list = sorted(example_list,key=lambda x: x*-1) >>> print(result_list) [7,0] (8) zip()
>>> a = [1,3] >>> b = [4,6] >>> c = [4,8] >>> zipped = zip(a,b) # 返回一个对象 >>> zipped 4、对象操作(9个) (1) help()
(2) dir()
>>> import math >>> math (3) id()
(4) hash()
>>>hash('test') # 字符串 2314058222102390712 >>> hash(1) # 数字 1 >>> hash(str([1,3])) # 集合 1335416675971793195 >>> hash(str(sorted({'1':1}))) # 字典 7666464346782421378 (5) type()
参数: name -- 类的名称。 bases -- 基类的元组。 dict -- 字典,类内定义的命名空间变量。 # 使用type函数创建类型D,含有属性InfoD >>> D = type('D',(A,B),dict(InfoD='some thing defined in D')) >>> d = D() >>> d.InfoD 'some thing defined in D' (6) len()
(7) ascii()
>>>a = ascii('paul你好') >>>print(a) 'paulu4f60u597d' (8) format()
>>>"{} {}".format("hello","world") # 不设置指定位置,按默认顺序 'hello world' >>> "{1} {0} {1}".format("hello","world") # 设置指定位置 'world hello world' print("网站名:{name},地址 {url}".format(name="菜鸟教程",url="www.runoob.com")) # 通过字典设置参数 site = {"name": "菜鸟教程","url": "www.runoob.com"} print("网站名:{name},地址 {url}".format(**site)) # 通过列表索引设置参数 my_list = ['菜鸟教程','www.runoob.com'] print("网站名:{0[0]},地址 {0[1]}".format(my_list)) # "0" 是**必须**的 输出: 网站名:菜鸟教程,地址 www.runoob.com class AssignValue(object): def __init__(self,value): self.value = value my_value = AssignValue(6) print('value 为: {0.value}'.format(my_value)) # "0" 是**可选**的 (9) vars()
>>>print(vars()) {'__builtins__': 5、反射操作(8个) (1) import()
(2) isinstance()
type() 不会认为子类是一种父类类型,==不考虑继承关系== isinstance() 会认为子类是一种父类类型,==考虑继承关系== ==如果要判断两个类型是否相同推荐使用isinstance()== >>> isinstance (a,(str,int,list)) # 是元组中的一个返回 True True class A: pass (3) issubclass()
>>> issubclass(bool,int) True >>> issubclass(bool,str) False >>> issubclass(bool,int)) True (4) hasattr()
>>> class Student: def __init__(self,name): self.name = name >>> s = Student('Aim') >>> hasattr(s,'name') #a含有name属性 True >>> hasattr(s,'age') #a不含有age属性 False (5) getattr()
>>>class A(object): ... bar = 1 ... >>> a = A() >>> getattr(a,'bar') # 获取属性 bar 值 1 >>> getattr(a,'bar2') # 属性bar2不存在,触发异常 Traceback (most recent call last): File " (6) setattr()
语法:setattr(object,name,value) #(对象,字符串/对象属性,属性值) >>>class A(object): ... bar = 1 ... >>> a = A() # 获取属性 bar 值 >>> getattr(a,'bar') 1 # 设置属性 bar 值 >>> setattr(a,'bar',5) >>> a.bar 5 (7) delattr()
(8) callable()
>>> class B: #定义类B def __call__(self): print('instances are callable now.') >>> callable(B) #类B是可调用对象 True >>> b = B() #调用类B >>> callable(b) #实例b是可调用对象 True >>> b() #调用实例b成功 6、变量操作(2个) (1) globals()
>>>a='runoob' >>>print(globals()) # globals 函数返回一个全局变量的字典,包括所有导入的变量。 {'__builtins__': (2) locals()
>>>def runoob(arg): # 两个局部变量:arg、z ... z = 1 ... print (locals()) ... >>> runoob(4) {'z': 1,'arg': 4} # 返回一个名字/值对的字典 7、交互操作(2个) (1) print()
(2) input()
8、文件操作(1个) (1) open() open(file,mode='r',buffering=-1,encoding=None,errors=None,newline=None,closefd=True,opener=None) file: 必需,文件路径(相对或者绝对路径) mode: 可选,文件打开模式 buffering: 设置缓冲 encoding: 一般使用utf8 errors: 报错级别 newline: 区分换行符 closefd: 传入的file参数类型 opener:
模式 描述 t 文本模式 (默认)。 x 写模式,新建一个文件,如果该文件已存在则会报错。 b 二进制模式。 + 打开一个文件进行更新(可读可写)。 U 通用换行模式(不推荐)。 r 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。 rb 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。一般用于非文本文件如图片等。 r+ 打开一个文件用于读写。文件指针将会放在文件的开头。 rb+ 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。一般用于非文本文件如图片等。 w 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。 wb 以二进制格式打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。一般用于非文本文件如图片等。 w+ 打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。 wb+ 以二进制格式打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。一般用于非文本文件如图片等。 a 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。 ab 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。 a+ 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。 ab+ 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。 9、编译执行(4个) (1) compile()
语法:compile(source,filename,mode[,flags[,dont_inherit]])
参数:
source -- 字符串或者AST(Abstract Syntax Trees)对象。。
filename -- 代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。
mode -- 指定编译代码的种类。可以指定为 exec,eval,single。
flags -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。
flags和dont_inherit是用来控制编译源码时的标志
>>>str = "for i in range(0,3): print(i)"
>>> c = compile(str,'exec') # 编译为字节代码对象
>>> c
(2) eval()
>>>x = 7 >>> eval( '3 * x' ) 21 >>> eval('pow(2,2)') 4 >>> eval('2 + 2') 4 >>> n=81 >>> eval("n + 4") 85 (3) exec()
x = 10 expr = """ z = 30 sum = x + y + z print(sum) """ def func(): y = 20 # 局部变量y exec(expr) exec(expr,{'x': 1,'y': 2}) exec(expr,'y': 2},{'y': 3,'z': 4}) # 在expr语句中,有三个变量x,y,z,其中z值已给定,我们可以在exec()函数外指定x,y的值,也可以在exec()函数中以字典的形式指定x,y的值。在最后的语句中,我们给出了x,z的值,并且y值重复,exec()函数接收后面一个y值,且z值传递不起作用,因此输出结果为34 (4) repr()
>>>s = 'RUNOOB' >>> repr(s) "'RUNOOB'" >>> dict = {'runoob': 'runoob.com','google': 'google.com'}; >>> repr(dict) "{'google': 'google.com','runoob': 'runoob.com'}" 10、装饰器(3个) (1) property
参数: fget -- 获取属性值的函数 fset -- 设置属性值的函数 fdel -- 删除属性值函数 doc -- 属性描述信息 # 将 property 函数用作装饰器可以很方便的创建只读属性 class Parrot(object): def __init__(self): self._voltage = 100000 (2) classmethod
class A(object): bar = 1 def func1(self): print ('foo') @classmethod def func2(cls): print ('func2') print (cls.bar) cls().func1() # 调用 foo 方法 (3) staticmethod
class C(object): @staticmethod def f(arg1,arg2,...): pass # 以上实例声明了静态方法f,类可以不用实例化就可以调用该方法C.f(),当然也可以实例化后调用C().f()。 class C(object): @staticmethod def f(): print('runoob'); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |