您现在的位置是:首页 > 文章详情

最全Python内置函数

日期:2018-08-04点击:423

内置函数的基本使用

abs的使用:

取绝对值

1 abs
print(abs(123))
print(abs(-123))

result:
123
123

all的使用:

循环参数,如果每个元素都为真的情况下,那么all的返回值为True:

假: 0, None, "", [],(), {} ret = all([True, True]) ret1 = all([True, False]) result: True False

any的使用:

只要有一个为True,则全部为True

ret = any(None, "", []) ret1 = any(None, "", 1) result: False True

ascii的使用:

回去对象的类中,找到__repr__方法,找到该方法之后获取返回值

class Foo: def __repr__(self): return "hello" obj = Foo() ret = ascii(obj ) 自动去对象(类)中找到 __repr__方法获取其返回值

bin的使用:

二进制

ret = bin(11) result: 0b1011

oct的使用:

八进制

ret = oct(14) result: 0o16

int的使用:

十进制

ret = int(10) result: 10

hex的使用:

十六进制

ret = hex(14) result: 0xe 0x:表示16进制 e: 表示14

bool的使用:

判断真假,  True:真  ,  False:假,   把一个对象转换成bool值

ret = bool(None) ret = bool(1) result: False True

bytearray的使用:

字节列表

列表元素是字节,

bytes的使用: 字节 bytes("xxx", encoding="utf-8")

callable的使用:

判断对象是否可被调用

class Foo: #定义类 pass foo = Foo() # 生成Foo类实例 print(callable(foo)) # 调用实例 ret = callable(Foo) # 判断Foo类是否可被调用 print(ret) result: False True 

chr的使用:

给数字找到对应的字符

ret = chr(65) result: A

ord的使用:

给字符找到对应的数字

ret = ord("a") result: a

classmethod的使用:

修饰符

修饰符对应的函数不需要实例化,不需要self参数,但第一个参数需要时表示自身类的cls参数,可以来调用类的属性,类的方法,实例化对象等。

class A(object): bar = 1 def func(self): print("func") @classmethod def func2(cls): print("func2") print(cls.bar) cls().func() # 调用func方法  A.func2() # 不需要实例化  result: func2 1 func

compile的使用:

函数讲一个字符串编译为字节代码

compile(source, filename, mode[, flags[, dont_inherit]]) 参数: source 字符串或者AST(Abstract Syntax Trees对象) filename 代码文件名称,如果不是从文件读取代码则传递一些可辨认的值 mode 指定编译代码的种类,可指定: exec, eval, single flags 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。 flags和dont_inherit是用来控制编译源码时的标志
str_for = "for i in range(1,10): print(i)" c = compile(str_for, '', 'exec') # 编译为字节代码对象 print(c) print(exec(c)) result: 1 2 3 4 5 6 7 8 9

complex的使用:

函数用于创建一个值为 real + image * j 的复数或者转化一个字符串或数为复数,如果第一个参数为字符串,则不需要指定第二个参数。

语法: class complex([real ,[ image]]) 参数说明: real int, long, float或字符串 image int,long,float
ret1 = complex(1,2) print(ret1) ret2 = complex(1) print(ret2) ret3 = complex("1") print(ret3) ret4 = complex("1+2j") print(ret4) result:返回一个复数 (1+2j) (1+0j) (1+0j) (1+2j)

delattr的使用:

用于删除属性

delattr(x, "foobar") 相等于 del x.foobar 语法: delattr(object, name) 参数: object 对象 name 必须是当前对象的属性
class DelClass: x = 10 y = -5 z = 0 obj = DelClass print("x", obj.x) print("y", obj.y) print("z", obj.z) delattr(DelClass, 'z') print("x", obj.x) print("y", obj.y) print("报错", obj.z) result: x 10 y -5 z 0 x 10 y -5 print("报错", obj.z) AttributeError: type object 'DelClass' has no attribute 'z'

dict的使用:

字典的使用方法

new_dict = dict() new_dict['key1'] = "test" print(new_dict)

dir的使用:

该方法将最大限制地收集参数信息, 查看当前,变量,方法, 类型的属性以及功能。

print(dir()) list_one = list() print(dir(list_one)) result: ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__'] ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__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']

divmod的使用:

将除数和余数运算结果结合起来,返回一个包含商和余数的元祖。

ret = divmod(7, 2) print(ret) ret_one = divmod(8, 2) print(ret_one) 参数: 数字 result: (3, 1) (4, 0)

enumerate的使用:

 用于将一个可遍历的数据对象(list, tuple,str)组合为一个索引序列,同时列出数据,和数据下标。

test_list = [1, 2, 3, 4, 5] for data_index, data in enumerate(test_list): print("下标:{0},数据{1}".format(data_index, data)) 参数: sequence 一个序列,迭代器或其他支持迭代对象 start 下标起始位置 result: 下标:0,数据1 下标:1,数据2 下标:2,数据3 下标:3,数据4 下标:4,数据5

eval的使用:

 用来执行一个字符串表达式,并且返回表达式的值

x = 7 ret = eval('x + 3') print(ret) 参数: expression 表达式 globals 变量作用域,全局命名空间 locals 变量作用域,局部命名空间 result: 10

exec的使用:

 执行存储在字符串或文件中的python语句,相比eval,exec可以执行更复杂的python代码

import time ret = exec("""for i in range(0,5): time.sleep(1) print(i) """) # 注意代码块中的缩进  result: 0 1 2 3 4

filter的使用:

 用于过滤序列,过滤掉不符合条件的元素,返回符合条件元素组成的新list

def is_odd(n): return n % 2 == 1 newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) print(newlist) 参数: function 判断函数 iterable 可迭代对象 result: [1, 3, 5, 7, 9]

float的使用:

将整形转换成小数形

a_int = 10 b_float = float(a_int) print(a_int) print(b_float) result: 10 10.0

format的使用:

字符串序列化,可以序列多种类型

str_format = "Helle World" list_format = ['list hello world'] dict_format = {"key_one":"value_one"} ret_format_one = "{0}".format(str_format) ret_format_two = "{0}".format(list_format) ret_format_three = "{0}".format(dict_format) print(ret_format_one) print(ret_format_two) print(ret_format_three) result: Helle World ['list hello world'] {'key_one': 'value_one'}

frozenset的使用:

 返回一个冻结集合,集合冻结之后不允许添加,删除任何元素

a = frozenset(range(10)) # 生成一个新的不可变集合 print(a) b = frozenset('wyc') # 创建不可变集合 print(b) result: frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9}) frozenset({'w', 'y', 'c'})

getattr的使用:

用于返回一个对象的属性值

class Foo(object): bar = 1 obj = Foo() print(getattr(obj, 'bar')) # 获取属性bar的默认值 print(getattr(obj, 'bar2')) # 不存在,没设置默认值,则报错 print(getattr(obj, 'bar2', 3)) # 属性2不存在,则设置默认值即可  result: 1 print(getattr(obj, 'bar2')) AttributeError: 'Foo' object has no attribute 'bar2' 3 

globals的使用:

会以字典类型返回当前位置的全部全局变量

print(globals()) result: {'__cached__': None, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__doc__': None, '__package__': None, '__file__': 'C:/Users/Administrator/PycharmProjects/untitled/day1.py', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000011E78626B70>, '__spec__': None} 

hasattr的使用:

 用于判断对象是否包含对应的属性

class Foo: x = 10 y = 20 z = 0 obj = Foo() print(hasattr(obj, 'x')) print(hasattr(obj, 'k')) result: True False

hash的使用:

 用于获取一个对象(字符串或者数值等)的哈希值

str_test = "wyc" int_test = 5 print(hash(str_test)) print(hash(int_test)) result: 1305239878169122869 5

help的使用:

帮助查看类型有什么方法

str_test = "wyc" print(help(str)) result: 结果有点小长,就不粘贴再此了 

id的使用:

查看当前类型的存储在计算机内存中的id地址

str_test = "wyc" print(id(str_test)) result: 2376957216616 

input的使用:

接受标准数据,返回一个string类型

user_input = input("请输入:") print(user_input) result: 请输入:wyc wyc

isinstance的使用:

 判断一个对象是否是一个已知的类型,类似type()

a = 1 print(isinstance(a, int)) print(isinstance(a, str)) result: True False

issubclass的使用:

 用于判断参数class是否是类型参数, classinfo的子类

class A: pass class B(A): pass print(issubclass(B, A)) # 判断B是否是A的子类  result: True

iter的使用:

 用来生成迭代器

lst = [1, 2, 3] for i in iter(lst): print(i) result: 1 2 3

len的使用:

查看当前类型里边有多少个元素

str_one = "hello world" lst = [1, 2, 3] print(len(str_one)) # 空格也会算一个元素 print(len(lst)) result: 11 3

list的使用:

列表

list = [1, 2, 3, 4, 5] 方法: 索引: index 切片: [1:3] 追加: append 删除: pop 长度: len 扩展: extend 插入: insert 移除:remove 反转: reverse 排序:sort

locals的使用:

 以字典类型返回当前位置的全部,局部变量

def func(arg): z = 1 return locals() ret = func(4) print(ret) result: {'arg': 4, 'z': 1}

map的使用:

 根据提供的函数对指定序列做映射

def func(list_num): return list_num * 2 print(map(func, [1, 2, 3, 4, 5])) result: [2, 4, 6, 8, 10]

max的使用:

返回最大数值

ret = max(1, 10) print(ret) result: 10

memoryview的使用:

 返回给定参数的内存查看对象

v = memoryview(bytearray("abc", 'utf-8')) print(v[0]) restlt: 97

min的使用:

 取出最小数值

print(min(1, 10)) result: 1

next的使用:

 返回迭代器的下一个项目

it = iter([1, 2, 3, 4, 5]) while True: try: x = next(it) print(x) except StopIteration: # 遇到StopIteration就退出循环 break result: 1 2 3 4 5

open的使用:

 打开一个文件,创建一个file对象,相关的方法才可以调用它的读写

f = open('test.txt') f.read() f.close() # 文件读写完成之后,一定要关闭

ord的使用:

函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常。

ret = ord('a') ret1 = ord('b') ret2 = ord('c') result: 97 98 99

pow的使用:

 返回 xy(x的y次方) 的值

import math # 导入 math 模块 print "math.pow(100, 2) : ", math.pow(100, 2) # 使用内置,查看输出结果区别 print "pow(100, 2) : ", pow(100, 2) print "math.pow(100, -2) : ", math.pow(100, -2) print "math.pow(2, 4) : ", math.pow(2, 4) print "math.pow(3, 0) : ", math.pow(3, 0)

print的使用:

 输出,打印

print('hello world') result: hello world

property的使用:

 新式类中的返回属性值,python3中是新式类,2中是旧式类

class C(object): def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.")

range的使用:

输出范围之内的数值

for i in range(1, 5): print(i) result: 1 2 3 4 5

repr的使用:

 函数将对象转化为供解释器读取的形式

s = 'RUNOOB' repr(s) "'RUNOOB'" dict = {'runoob': 'runoob.com', 'google': 'google.com'}; repr(dict) "{'google': 'google.com', 'runoob': 'runoob.com'}"

reversed的使用:

 返回一个反转的迭代器

# 字符串 seqString = 'Runoob' print(list(reversed(seqString))) # 元组 seqTuple = ('R', 'u', 'n', 'o', 'o', 'b') print(list(reversed(seqTuple))) # range seqRange = range(5, 9) print(list(reversed(seqRange))) # 列表 seqList = [1, 2, 4, 3, 5] print(list(reversed(seqList))) result: ['b', 'o', 'o', 'n', 'u', 'R'] ['b', 'o', 'o', 'n', 'u', 'R'] [8, 7, 6, 5] [5, 3, 4, 2, 1]

round的使用:

 返回浮点数x的四舍五入值

print "round(80.23456, 2) : ", round(80.23456, 2) print "round(100.000056, 3) : ", round(100.000056, 3) print "round(-100.000056, 3) : ", round(-100.000056, 3) result: round(80.23456, 2) : 80.23 round(100.000056, 3) : 100.0 round(-100.000056, 3) : -100.0

set的使用:

 不可重复元素

a=set((1,2,3,"a","b"))

setattr的使用:

设置属性值,该属性必须存在

class A(object): bar = 1 a = A() print(getattr(a, 'bar')) # 获取属性 bar 值 1 setattr(a, 'bar', 5) # 设置属性 bar 值 print(a.bar)

slice的使用:

  实现切片对象,主要用在切片操作函数里的参数传递

myslice = slice(5) # 设置截取5个元素的切片 print(myslice) print(slice(None, 5, None)) arr = range(10) print(arr) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(arr[myslice]) # 截取 5 个元素 [0, 1, 2, 3, 4]

 

sorted的使用:

 所有可迭代的对象进行排序操作

a = [5,7,6,3,4,1,2] b = sorted(a) # 保留原列表 print(a) [5, 7, 6, 3, 4, 1, 2] print(b) [1, 2, 3, 4, 5, 6, 7] L=[('b',2),('a',1),('c',3),('d',4)] sorted(L, cmp=lambda x,y:cmp(x[1],y[1])) # 利用cmp函数 [('a', 1), ('b', 2), ('c', 3), ('d', 4)] print(sorted(L, key=lambda x:x[1])) # 利用key [('a', 1), ('b', 2), ('c', 3), ('d', 4)] students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] print(sorted(students, key=lambda s: s[2]) ) # 按年龄排序 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] print(sorted(students, key=lambda s: s[2], reverse=True) ) # 按降序 [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

staticmethod的使用:

 返回函数的静态方法

class C(object): @staticmethod def f(): print('runoob'); C.f(); # 静态方法无需实例化 cobj = C() cobj.f() # 也可以实例化后调用

str的使用:

 字符串

str = "wyc" 方法: cpitalize 首字母变大写 count 子序列个数 decode 解码 encode 编码针对unicode endswith 是否以xxx结束 find 寻找子序列位置,如果没有找到,返回-1 format 字符串格式化 index 子序列位置,如果没有找到,报错 isalnum 是否是字母数字 isalpha 是否是字母 isdigit 是否是数字 islower 是否小写 join 拼接 lower 变小写 lstrip 移除左侧空白 replace 替换

sum的使用:

求数值整合

print(sum(1+1)) result: 2

super的使用:

 用于调用父类(超类)的一个方法

Python3.x 和 Python2.x 的一个区别是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx python3 class A: pass class B(A): def add(self, x): super().add(x) python2 class A(object): # Python2.x 记得继承 object pass class B(A): def add(self, x): super(B, self).add(x)

tuple的使用:

元祖,元祖是不可修改的

tuple = (1, 2, 3)

type的使用:

查看当前类型是什么类型

lst = list() print(type(lst)) result: <class 'list'>

vars的使用:

 返回对象object的属性和属性值的字典对象

print(vars()) {'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None} class Runoob: a = 1 print(vars(Runoob)) {'a': 1, '__module__': '__main__', '__doc__': None} runoob = Runoob() print(vars(runoob)) {}

zip的使用:

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

如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

a = [1,2,3] b = [4,5,6] c = [4,5,6,7,8] zipped = zip(a,b) # 打包为元组的列表 [(1, 4), (2, 5), (3, 6)] zip(a,c) # 元素个数与最短的列表一致 [(1, 4), (2, 5), (3, 6)] zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式 [(1, 2, 3), (4, 5, 6)]

__import__的使用:

 函数用于动态加载类和函数 

import time, os

扩展进制转换:

二进制转换十进制 int('0b11', base=2) result: 3 八进制转换十进制 int('11', base=8) result: 9 十六进制转换十进制 int('0xe', base=16) result: 14

以上有不足之处,请大神,留下宝贵的建议,本人看到第一时间添加。

原文链接:https://yq.aliyun.com/articles/629454
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章