python3 内置函数

内置函数BIF(built-in-functions):能直接用的函数

一.数学运算

1.abs():求数值的绝对值

2.max()、min():求最大最小值

3.pow(x,y):x的y次幂

4.sum():求和

5.round():对浮点数进行四舍五入求值

6.divmod():返回两个数值的商和余数

 

二.转换

1.int([x[, base]])、float(x)、boolean()、complex()、str([object])、list([iterable])、tuple([iterable]) 、dict([arg])、set()、frozenset()、object:根据传入的参数创建一个新的整数,浮点数,布尔类型、复数,字符串,列表,元组,字典,可变集合,不可变集合、object对象

2.数字进制转化:bin(x)、oct(x)、hex()、将十进制数转换成2进制字符串、8进制字符串、16进制字符串

3.ord()、chr():返回ASCII字符/对应的十进制数,返回十进制数所对应的ASCII字符/

4.bytes():根据传入的参数创建一个新的不可变字节数组(比如将一个字符串转换成字节类型);bytearray():根据传入的参数创建一个新的字节数组,数组里的元素是可变的,范围 [0,256)

5.转换为字符串类型:str()和repr()以及ascii()

(1)str():函数返回一个用户易读的表达形式;

(2)repr(): 产生一个解释器易读的字符串表达形式(repr() 函数可以转义字符串中的特殊字符)

(3)ascii() :类似 repr() 函数, 返回一个表示对象的字符串,对于字符串中的非 ASCII 字符则返回通过 repr() 函数使用 \x, \u 或 \U 编码的字符

6.compile() 函数将一个字符串编译为字节代码,使之能够通过exec语句来执行或者eval进行求值,compile(source, filename, mode[, flags[, dont_inherit]])

7.执行函数:eval() 函数和exec()函数

(1)eval() 函数用来执行一个字符串表达式,并返回表达式的值,eval(expression[, globals[, locals]])

(2)exec 执行储存在字符串或文件中的 Python 语句,相比于 eval,exec可以执行更复杂的 Python 代码,exec(object[, globals[, locals]])

 1 #eval() 函数用来执行一个字符串表达式,返回表达式计算结果
 2 print(eval('pow(2,2)'))
 3 a='8'
 4 b=eval(a)
 5 c='b'# 等价于c='8'
 6 d=eval(c)
 7 print(a,type(a))
 8 print(b,type(b))# 还可以将字符串对应的名字的变量转换成该变量对应的值
 9 print(c,type(c))
10 print(d,type(d))
11 
12 #exec 执行储存在字符串或文件中的 Python 语句,返回表达式执行结果
13 str = "for i in range(0,10): print(i)"
14 x= compile(str,'','exec')   # 编译为字节代码对象
15 print(x)
16 exec(x)
17 exec('print("Hello World")')
18 exec ("""for i in range(5):
19      print ("iter time: %d" % i)
20  """)
21 ----------------------------------------------------------
22 4
23 8 <class 'str'>
24 8 <class 'int'>
25 b <class 'str'>
26 8 <class 'int'>
27 <code object <module> at 0x04E5A230, file "", line 1>
28 0
29 1
30 2
31 3
32 4
33 5
34 6
35 7
36 8
37 9
38 Hello World
39 iter time: 0
40 iter time: 1
41 iter time: 2
42 iter time: 3
43 iter time: 4
eval()和exec()

 

三.序列

1.range():根据传入的参数创建一个新的range对象

2.enumerate():根据可迭代对象创建枚举对象

3.iter():根据传入的参数创建一个新的可迭代对象

4.slice():根据传入的参数创建一个新的切片对象

5.super():根据传入的参数创建一个新的子类和父类关系的代理对象,调用父类方法

 

四.序列操作

1.all(iterable):判断可迭代对象的每个元素是否都为True值,特别的,若为空串返回为True

2.any(iterable):判断可迭代对象的元素是否有为True值的元素,特别的,若为空串返回为False

3.sorted(iterable, key=None, reverse=False):对可迭代对象进行排序,返回一个新的列表,reversed:反转序列生成新的可迭代对象

4.len(object):返回对象(字符、列表、元组等)长度或项目个数

 

五.常用函数

1.查询变量类型:type() 函数和isinstance() 函数

(1)type() 函数如果你只有第一个参数则返回对象的类型,三个参数返回新的类型对象

(2)isinstance() 函数来判断一个对象是否是一个已知的类型

 1 a=111
 2 type(a)
 3 print(type(a))                     #查询变量所指的对象类型
 4 print(isinstance(a,str))           #判断变量是否是某个类型
 5 print(isinstance(a,(str,int,list)))#是元组中的一个返回 True
 6 
 7 # sinstance() 与 type() 区别:
 8 # type() 不会认为子类是一种父类类型,不考虑继承关系。
 9 # isinstance() 会认为子类是一种父类类型,考虑继承关系。
10 # 如果要判断两个类型是否相同推荐使用 isinstance()。
11 class A:
12     pass
13 class B(A):
14     pass
15 print(isinstance(A(), A))
16 print(type(A()) == A)
17 print(isinstance(B(), A))   #isinstance()会认为子类是一种父类类型,所以返回True
18 print(type(B()) == A)       #type()不会认为子类是一种父类类型,所以返回False
19 --------------------------------------------------------------------------------------------
20 <class 'int'>
21 False
22 True
23 True
24 True
25 True
26 False
type()和isinstance()

2.查询对象方法:dir()和help()

(1)dir([object])返回模块的属性列表,比如查询一个类或者对象的所有方法名称

(2)help([object])返回对象帮助信息,用于查看函数或模块用途的详细说明

 1 print(dir())       # 获得当前模块的属性列表
 2 print(dir([ ]))    # 查看列表的方法
 3 help('str')        # 获取对象的帮助说明文档
 4 
 5 name = 'str'
 6 print(dir(name))  # 简列功能名称
 7 help(type(name))  # 详细列出功能说明
 8 -------------------------------------------------------
 9 ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
10 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
11 Help on class str in module builtins:
12 
13 class str(object)
14  |  str(object='') -> str
15  |  str(bytes_or_buffer[, encoding[, errors]]) -> str
16  |  
17  |  Create a new string object from the given object. If encoding or
18  |  errors is specified, then the object must expose a data buffer
19  |  that will be decoded using the given encoding and error handler.
20  |  Otherwise, returns the result of object.__str__() (if defined)
21  |  or repr(object).
22  |  encoding defaults to sys.getdefaultencoding().
23  |  errors defaults to 'strict'.
24  |  
25  |  Methods defined here:
26  |  
27  |  __add__(self, value, /)
28  |      Return self+value.
29  |  
30  |  __contains__(self, key, /)
31  |      Return key in self.
32 ........................................
33 ...
34 
35 ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
36 Help on class str in module builtins:
37 
38 class str(object)
39  |  str(object='') -> str
40 
41 ..........................
dir()和help()

3.删除属性:delattr()函数(delattr(x, 'foobar') 相等于 del x.foobar)和关键字del 操作

(1)delattr(object, name)该函数有两个参数object -- 对象,name -- 必须是对象的属性

(2)del关键字用于删除对象,可以删除部分序列,也可以删除整个对象

 1 class A:
 2     def __init__(self, name):
 3         self.name = name
 4 
 5     def sayHello(self):
 6         print('hello', self.name)
 7 a=A('xiao')
 8 print(a.name)
 9 print(a.sayHello())
10 --------------------------------
11 xiao
12 hello xiao
13 None
14 
15 #delatter
16 delattr(a,'name')    #删除属性‘name’
17 print(a.name)        #报错 AttributeError: 'A' object has no attribute 'name'
18 
19 #del
20 del a                #删除对象a
21 print(a)             #报错NameError: name 'a' is not defined
delatter()和del

4. getattr() 函数和setattr() 函数和hasattr()函数以及vars()函数

(1)getattr() 函数用于返回一个对象属性值,getattr(object, name[, default])

(2)setattr() 函数用于设置属性值,该属性必须存在,setattr(object, name, value)

 1 #object -- 对象,name -- 字符串,对象属性,
 2 #default -- 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError
 3 # value -- 属性值
 4 class A(object):
 5    bar = 1
 6 
 7 a = A()
 8 print(getattr(a, 'bar'))   #获取属性bar值
 9 #print(getattr(a, 'bar2')) #获取属性bar2值,若不存在则触发异常AttributeError: 'A' object has no attribute 'bar2'
10 print(getattr(a, 'bar3', 3))#属性bar3不存在,但设置了默认值)
11 setattr(a,'bar',2)         #设置属性 bar 值
12 print(getattr(a, 'bar'))   #再次获取属性bar值,可以看到bar的值改变了
13 ------------------------------------------------------------------------
14 1
15 3
16 2
getattr()和setattr()

(3)hasattr() 函数用于判断对象是否包含对应的属性,hasattr(object, name),返回True或False

1 class A(object):
2    bar = 1
3 
4 a = A()
5 print(hasattr(a,'bar'))
6 print(hasattr(a,'bar2'))
7 ---------------------------------------------
8 True
9 False
hasattr()

(4)vars() 函数返回对象object的属性和属性值的字典对象

 1 #vars()返回对象object的属性和属性值的字典对象,如果没有参数,就打印当前调用位置的属性和属性值 类似 locals()
 2 print(vars())
 3 class Runoob:
 4    a = 1
 5 print(vars(Runoob))
 6 runoob = Runoob()
 7 print(vars(runoob))
 8 ------------------------------------------------------------------------------
 9 {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0550C470>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/python_work/example/2018.4.8.py', '__cached__': None}
10 {'__module__': '__main__', 'a': 1, '__dict__': <attribute '__dict__' of 'Runoob' objects>, '__weakref__': <attribute '__weakref__' of 'Runoob' objects>, '__doc__': None}
11 {}
vars()

5.id() 函数用于获取对象的内存地址

6.globals() 函数和locals() 函数

(1)globals() 函数会以字典类型返回当前位置的全部全局变量

(2)locals() 函数会以字典类型返回当前位置的全部局部变量

 1 a='runoob'
 2 def runoob(arg):    # 两个局部变量:arg、z
 3     z = 1
 4     print (locals())#打印当前位置的全部局部变量,并以字典形式返回
 5 
 6 runoob(4)
 7 print(globals()) # globals 函数返回一个全局变量的字典,包括所有导入的变量。
 8 
 9 -------------------------------------------------------------------------------------
10 {'z': 1, 'arg': 4}
11 {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0591C470>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/python_work/example/2018.4.8.py', '__cached__': None, 'a': 'runoob', 'runoob': <function runoob at 0x05A353D8>}
globals()和locals()

7.open() 函数用于打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写

8.输入输出函数input()和print()

9.format():格式化显示值

 

六.其他

1.hash:获取对象的哈希值

2.memoryview:根据传入的参数创建一个新的内存查看对象

3.迭代器方法:iter() 函数用来生成迭代器,next() 返回迭代器的下一个项目

4.过滤序列:filter() 函数,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表

 1 #filter(function or None, iterable)--> filter object
 2 ##该接收两个参数,第一个为函数,第二个为序列,
 3 # 序列的每个元素作为参数传递给函数进行判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中
 4 print(filter(None,[1,0,False,True]))#筛选出True的内容,
 5 print(list(filter(None,[1,0,False,True])))#过滤掉0和False的内容
 6 
 7 #生成奇数列表
 8 def odd(x):
 9     return x%2
10 temp=range(10)
11 show=filter(odd,temp)#在1~10的序列中筛选出满足函数的True的内容,
12 # 也就是temp(1~10)中求余为1的数
13 print(list(show))
14 #相当于:
15 print(list(filter(lambda  x:x%2,range(10))))
16 -----------------------------------------------------------------------
17 <filter object at 0x056D13D0>
18 [1, True]
19 [1, 3, 5, 7, 9]
20 [1, 3, 5, 7, 9]
filter()

5.映射函数:map()函数,map() 会根据提供的函数对指定序列做映射,第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表

 1 #map(function, iterable, ...)根据提供的函数对指定序列做映射
 2 #如果函数有多个参数, 但每个参数的序列元素数量不一样, 会根据最少元素的序列进行
 3 def square(x) :            # 计算平方数
 4    return x ** 2
 5 print(list(map(square, [1,2,3,4,5])))
 6 print(list(map(lambda  x:x%2,range(10))))
 7 print(list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])))## 提供了两个列表,对相同位置的列表数据进行相加
 8 -----------------------------------------------------------------------------------
 9 [1, 4, 9, 16, 25]
10 [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
11 [3, 7, 11, 15, 19]
map()

6.zip()函数,用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表

 1 #zip([iterable, ...])将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表
 2 a = [1,2,3]
 3 b = [4,5,6]
 4 c = [4,5,6,7,8]
 5 print(zip(a,b))
 6 print(list(zip(a,b))) # 打包为元组的列表
 7 print(list(zip(b,c))) # 元素个数与最短的列表一致
 8 zipped=zip(a,c)
 9 d=zip(*zipped)        #利用 * 号操作符,可以将元组解压为列表
10 print(list(d))        #与 zip 相反,可理解为解压,返回二维矩阵式
11 
12 
13 #列表元素依次相连
14 l = ['a', 'b', 'c', 'd', 'e','f']
15 print (list(zip(l[:-1],l[1:])))
16 ----------------------------------------------------------------------
17 <zip object at 0x04A8B508>
18 [(1, 4), (2, 5), (3, 6)]
19 [(4, 4), (5, 5), (6, 6)]
20 [(1, 2, 3), (4, 5, 6)]
21 [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e'), ('e', 'f')]
zip()

7.issubclass() 方法用于判断参数 class 是否是类型参数 classinfo 的子类,issubclass(class, classinfo)

8.property() 函数的作用是在新式类中返回属性值,class property([fget[, fset[, fdel[, doc]]]])

9.staticmethod()返回函数的静态方法

10.callable() 函数用于检查一个对象是否是可调用的,如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功

11.装饰器:property(),staticmethod()和classmethod()

(1)property() :标示属性的装饰器,在新式类中返回属性值,

(2)staticmethod:标示方法为静态方法的装饰器,返回函数的静态方法

 1 #staticmethod(function)该方法不强制要求传递参数
 2 # 使用装饰器定义静态方法(通过类直接调用,不需要创建对象,不会隐式传递self)
 3 class C(object):
 4     @staticmethod
 5     def f():
 6         print('runoob');
 7 
 8 C.f()  # 静态方法无需实例化
 9 cobj = C()
10 cobj.f()  # 也可以实例化后调用
11 -----------------------------------------------------------------------
12 runoob
13 runoob
staticmethod()

(3)classmethod:标示方法为类方法的装饰器,返回函数的类方法

 

posted on 2018-05-28 20:16  温润有方  阅读(326)  评论(0编辑  收藏  举报