1.内置函数列表如下:
内 | 置 | 函 | 数 | |
---|---|---|---|---|
abs() | dict() | help() | min() | setattr() |
all() | dir() | hex() | next() | slice() |
any() | divmod() | id() | object() | sorted() |
ascii() | enumerate() | input() | oct() | staticmethod() |
bin() | eval() | int() | open() | str() |
bool() | exec() | isinstance() | ord() | sum() |
bytearray() | filter() | issubclass() | pow() | super() |
bytes() | float() | iter() | print() | tuple() |
callable() | format() | len() | property() | type() |
chr() | frozenset() | list() | range() | vars() |
classmethod() | getattr() | locals() | repr() | zip() |
compile() | globals() | map() | reversed() | __import__() |
complex() | hasattr() | max() | round() | |
delattr() | hash() | memoryview() | set() |
2.内置函数讲解
1. abs(): 返回数字绝对值
2. all(): 判断给定的可迭代对象iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。元素除了0,
NULL, False为全部为True。
any(): 判断给定的可迭代参数 iterable 是否全部为 False,全为False返回 False,如果有一个为 True,则返回 True。
元素除了是 0、空、FALSE 外都算 TRUE。
print(all([0, 1, -1])) # False
print(all([-3, 1, -1])) # True
print(all([-3, "", -1])) # False
print(any([0, 0, 0])) # False
print(any([1, 0, 0])) # True
print(any([-1, 0, 0])) # True
print(any([])) # False
3. ascii(): 类似 repr() 函数, 返回一个表示对象的字符串, 但是对于字符串中的非 ASCII 字符则返回通过 repr() 函数使用 \x, \u 或 \U 编码的字符。生成字符串类似 Python2 版本中 repr() 函数的返回值。
repr(): 返回对象的规范字符串表示形式。对于许多对象类型,包括大多数内置函数,eval(repr(obj))== obj
# ascii()
# \x为utf-8的编码格式
# \u为Unicode编码格式
print(ascii(12612345567789999)) # '12612345567789999'
print(ascii("abcfg")) # 'abcfg'
print(ascii([1, 2, 3])) # '[1, 2, 3]'
print(ascii({"name": "mx"})) # '{"name": "mx"}'
print(ascii("我")) # '\u6211'
# repr()
# 返回对象的规范字符串表示形式。对于许多对象类型,包括大多数内置函数,eval(repr(obj))== obj
a = [1, 2]
b = eval(repr(a))
print(a, b, type(a), type(b)) # [1, 2] [1, 2] <class 'list'> <class 'list'>
4. bin(): 返回一个整数的二进制表示形式。(python3中全部为整形,没有长整型)
# bin()
print(bin(1)) # 0b1
print(bin(2)) # 0b10
print(bin(255)) # 0b11111111
print(bin(256)) # 0b100000000
5. bytearray(): 返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256
注意:数组为可变数组。以a3为例,想要修改第一个字母t为a, a[0] = 97。(此时可修改,别忘了字符串本身不可修改)
bytes(): bytearray()的不可变版本。
# bytearray()
# 返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256
# (1) 如果没有输入任何参数,默认就是初始化数组为0个元素。
# (2) 如果 source 为整数,则返回一个长度为source且初始化元素为\x00的初始化数组
# (3) 如果 source 为字符串,则按照指定的 encoding 将字符串转换为字节序列
# (4) 如果 source 为可迭代类型,则元素必须为[0 ,255] 中的整数
# (5) 如果 source 为与 buffer 接口一致的对象,则此对象也可以被用于初始化 bytearray。
a1 = bytearray() # bytearray(b'')
a2 = bytearray(10) # a2: bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
a3 = bytearray("test", encoding="utf-8") # bytearray(b'test')
a4 = bytearray([1, 3, 255]) # bytearray(b'\x01\x03\xff')
6. callable(): 用于检查一个对象是否是可调用的。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。函数, lambda 匿名函数, 类, 以及实现了 __call__ 方法的类实例, 它都返回 True。
def test():
pass
class A(object):
def produce(self):
pass
class B(object):
def __call__(self, *args, **kwargs):
pass
if "__main__" == __name__:
a = A()
b = B()
print(callable(test)) # True
print(callable(lambda x: x)) # True
print(callable(a.produce())) # False
print(callable(A)) # True
print(callable(B)) # True
print(callable(a)) # False
print(callable(b)) # True
7. classmethod(): 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等
# classmethod
class C(object):
bar = "bar"
def __init__(self):
print("this is init")
@classmethod
def test(cls):
print("this is test()")
print(cls)
print(cls.bar)
print(cls().__init__())
c = C()
C.test()
c.test()
8. exec(): 执行储存在字符串或文件中的 Python 语句,相比于 eval,exec可以执行更复杂的 Python 代码
eval(): 执行一个字符串表达式,并返回表达式的值。
【注意】:globals={}和locals={}相当于对expression中的变量进行赋值。
# eval()
# 执行一个字符串表达式,并返回表达式的值。
# eval(expression, globals, locals)
# expression -- 表达式
# globals -- 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。
# locals -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。
print(eval("1+2")) # 3
print(eval("3*8")) # 24
print(eval("pow(2, 4)")) # 16
a = 520
expr = "a + 1"
print(eval(expr)) # 521
def test():
print(eval(expr, {"a": 520}, {"a": 1})) # 2
test()
# exec()
# 执行储存在字符串或文件中的 Python 语句,相比于 eval,exec可以执行更复杂的 Python 代码
# exec(object, globals, locals)
# object:必选参数,表示需要被指定的Python代码。它必须是字符串或code对象。如果object是一个字符串,该字符串会先被解析为一组Python语句,然后在执行(除非发生语法错误)。如果object是一个code对象,那么它只是被简单的执行。
# globals:可选参数,表示全局命名空间(存放全局变量),如果被提供,则必须是一个字典对象。
# locals:可选参数,表示当前局部命名空间(存放局部变量),如果被提供,可以是任何映射对象。如果该参数被忽略,那么它将会取与globals相同的值。
exec("""for i in range(5):
print ("iter time: %d" % i)
""")
x = 10
expr = """
z = 30
sum = x + y + z
print(sum)
"""
def func():
y = 20
exec(expr) # 60
exec(expr, {'x': 1, 'y': 2}) # 33
exec(expr, {'x': 1, 'y': 2}, {'y': 3, 'z': 4}) # 34
func()
9. compile(): 将一个字符串编译为字节代码。
complex(): 创建一个值为 real + imag * j 的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。real(实部): int, float, str ---- imag(虚部): int, float
# 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,10): print(i)"
c = compile(str, "", "exec")
exec(str)
exec(c)
# complex()
# class complex(real, imag)
print(complex(1))
print(complex(1.0))
print(complex("1.0"))
print(complex(1, 2))
print(complex(1, 2.0))
print(complex("1 + 2j"))
10. delattr(): 删除类实例化对象的属性。
getattr(): 返回一个对象的属性值。
hasattr(): 判断对象、类,是否包含对应的属性。
setattr(): 用于设置属性值,且该属性必须存在。
# delattr()
# delattr(object, name)
# 删除类实例化对象的属性
class Cooperation(object):
a = 1
b = 2
c = 3
@staticmethod
def test():
print("this is test")
p = Cooperation()
print("a:", p.a, "b:", p.b, "c:", p.c)
Cooperation.test()
print("----------删除c属性后----------")
delattr(Cooperation, "c")
# delattr(Cooperation, "test") # error
print(getattr(Cooperation, "b"))
print(getattr(p, "b"))
# ---------------------------------------------------------------------------------------
# hasattr()
# 判断对象、类是否包含对应的属性
# hasattr(object, name)
# name: 属性名(字符串)
class Coordinate(object):
a = 1
def __init__(self):
self.b = 2
def test(self):
print("this is test function")
p = Coordinate()
print(hasattr(p, "a")) # True
print(hasattr(p, "b")) # True
print(hasattr(p, "test")) # True
print(hasattr(Coordinate, "a")) # True
print(hasattr(Coordinate, "b")) # False
print(hasattr(Coordinate, "test")) # True
# ---------------------------------------------------------------------------------------
# setattr()
# 设置对象属性值
# setattr(object, name, value)
setattr(p, "a", 44)
setattr(p, "b", 55)
print(getattr(p, "a", "error")) # 44
print(getattr(p, "b", "error")) # 55
11. dir(): 不带参数时,返回当前范围内的变量、函数、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。
divmod(): 把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)。python 2.3 版本之前不允许处理复数。
# dir()
# dir(object)
# 不带参数时,返回当前范围内的变量、函数、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。
# 如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。
a = 1
class D(object):
b = 2
def __init__(self):
self.c = 3
print("dir1:\n", dir()) # ['self']
print("dir2:\n", dir()) # ['__dir__', '__init__', '__module__', '__qualname__', 'b']
def test2():
d = 2
d1 = D()
print("dir3:\n", dir()) # ['D', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'd1', 'test2']
# divmod()
# divmod(num1, num2)
# 把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b)。python 2.3 版本之前不允许处理复数。
dm = divmod(7, 2)
dm = divmod(7.5, 2)
print(dm, type(dm))
print("divisor:", dm[0], "\nremainder:", dm[1])
12. enumerate(): 用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。重要应用:文件的高效读取(生成器)。
# enumerate()
# 用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
# 重要应用:文件的高效读取(生成器)
# enumerate(sequence, start)
# sequence: 一个序列、迭代器或其他支持迭代对象
# start: 下标开始编号的起始位置
f = open("test.txt", "r", encoding="utf-8")
print(type(f))
for index, line in enumerate(f):
print(index, line)
f.close()
13. filter(): 用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中
map(): 将函数依次作用于可迭代对象的每一个元素,每次作用的结果储存于返回的迭代器中。(python3中返回迭代器)。function可以有多个参数, 同时对应相加的可迭代对象也应增加。停止的条件以最短的可迭代对象为准。
两者的区别:filter是通过生成True和False组成的迭代器将可迭代对象中不符合条件的元素过滤掉;而map返回的则是True和False组成的迭代器。
# filter()
# 用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。
# 该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中
# filter(function, iterable)
itb = filter(lambda x: x%2 == 0, range(10))
# for item in itb:
# print(item)
newlist = list(itb)
print(newlist)
# map()
# 将函数对象依次作用于表的每一个元素,每次作用的结果储存于返回的表re中
# map(function, iterable)
res1 = map(lambda n: n > 5, range(10))
lt1 = list(res1)
print(lt1) # [False, False, False, False, False, False, True, True, True, True]
res3 = map(lambda x, y: x+y, range(10), range(10))
for i in res3:
print(i)
res4 = map(lambda x, y: x+y, range(10), range(5))
for i in res4:
print(i)
# ----------------------------------------区 别-------------------------------------- #
res2 = filter(lambda n: n > 5, range(10))
lt = list(res2)
print(lt) # [6, 7, 8, 9]
14. format(): python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。基本语法是通过 {} 和 : 来代替以前的 %。format 函数可以接受不限个参数,位置可以不按顺序。str.format() 格式化数字也有多种方法。
注意:格式化数字的常用方式
数字 格式 输出 描述 3.1415926 {:.2f} 3.14 保留小数点后两位 3.1415926 {:+.2f} +3.14 带符号保留小数点后两位 -1 {:+.2f} -1.00 带符号保留小数点后两位 2.71828 {:.0f} 3 不带小数 5 {:0>2d} 05 数字补零 (填充左边, 宽度为2) 5 {:x<4d} 5xxx 数字补x (填充右边, 宽度为4) 10 {:x<4d} 10xx 数字补x (填充右边, 宽度为4) 1000000 {:,} 1,000,000 以逗号分隔的数字格式 0.25 {:.2%} 25.00% 百分比格式 1000000000 {:.2e} 1.00e+09 指数记法 13 {:10d} 13 右对齐 (默认, 宽度为10) 13 {:<10d} 13 左对齐 (宽度为10) 13 {:^10d} 13 中间对齐 (宽度为10) 11 '{:b}'.format(11) '{:d}'.format(11) '{:o}'.format(11) '{:x}'.format(11) '{:#x}'.format(11) '{:#X}'.format(11)
1011 11 13 b 0xb 0XB
进制
# format()
# Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
# 基本语法是通过 {} 和 : 来代替以前的 %
# format 函数可以接受不限个参数,位置可以不按顺序
# str.format() 格式化数字也有多种方法
# 1.不设置制定位置,按照默认顺序
print("{} {}".format("my", "brother"))
# 2.设置指定位置
print("{1} {0}".format("my", "brother"))
# 3.关键词参数设置
dt = {"name": "maxin", "age": 23}
lt = ["maxin", 23]
tp = ("maxin", 23)
print("姓名:{name}, 年龄:{age}".format(**dt))
print("姓名:{0[0]}, 年龄:{0[1]}".format(lt)) # 0是必须的
print("姓名:{0[0]}, 年龄:{0[1]}".format(tp)) # 0是必须的
# 4.format()可传入对象
class FmTest(object):
def __init__(self, value=24):
self.value = value
my_value = FmTest(250)
print("value:{0.value}".format(my_value)) # 0是必须的
# 5.format()格式化数字
print("{:.2f}".format(2.1463456))
print("{:0>5d}".format(2))
print("{:0<5d}".format(2))
print("{:0^5d}".format(2))
15. globals(): 以字典类型返回当前位置的全部全局变量
locals(): 以字典类型返回当前位置的全部局部变量。对于函数, 方法, lambda 函式, 类, 以及类实例, 它都返回 True。
# globals()
# locals()
a = 1
def test():
b = 2
print("test locals():", locals())
def test_in():
print("test_in locals():", locals())
c = lambda x: x+5
class Ta(object):
d = 4
print("Ta locals():", locals())
def __init__(self):
self.e = 5
print("__init__ locals():", locals())
test()
ta = Ta()
print(globals())
print("locals():", locals())
16. hash(): 获取一个对象、字符串、数值的哈希值。在 hash() 对对象使用时,所得的结果不仅和对象的内容有关,还和对象的 id(),也就是内存地址有关。
# hash()
# hash(object)
# 可以应用于数字、字符串和对象,不能直接应用于 list、dictionary、set。
# 在 hash() 对对象使用时,所得的结果不仅和对象的内容有关,还和对象的 id(),也就是内存地址有关。
class Test(object):
def __init__(self, i):
self.i = i
for i in range(10):
t = Test(i)
print(hash(t), id(t))
print(hash(str([1, 2])))
print(hash((1, 2)))
print(hash(str({"name": "maxin"})))
print(hash(str(set([1, 2]))))
17. isinstance(): 判断一个对象是否是一个已知的类型,类似 type()。
type(): 如果你只有一个参数则返回对象的类型。三个参数返回新的类型对象。
两者区别:isinstance()考虑子类与父类之间的继承关系;type()并不考虑子类与父类之间的继承关系。若判断两个类型是否相同最好使用isinstance()函数。
issubclass(): 判断类A是否是类B的子类
# isinstance()
# 判断一个对象是否是一个已知的类型,类似 type()
# isinstance(object, classinfo)
# object: 实例对象
# classinfo: 可以是直接或间接类名、基本类型或者由它们组成的元组。
a = 2
print(isinstance(a, str))
print(isinstance(a, int))
print(isinstance(a, (str, int)))
# type()
# 如果你只有第一个参数则返回对象的类型,三个参数返回新的类型对象。
# class type(name, bases, dict)
# name: 类名称
# bases: 基类元组((object))
# dict: 字典,类内定义的命名空间变量。
# 1.一个参数
print(type(1))
print(type([]))
print(type({}))
print(type(()))
# 2.三个参数
Te = type("Te", (object,), dict(a=1)) # 产生一个新的类型 X
print(Te)
# ---------------------------------------两者区别----------------------------------------#
class A(object):
pass
class B(A):
pass
print(isinstance(A(), A)) # True
print(type(A()) == A) # True
print(isinstance(B(), A)) # True
print(type(B()) == A) # False
# issubclass()
# issubclass(class, classinfo)
# 判断class(类)是否是classinfo(类)的子类
print(issubclass(B, A)) # True
print(issubclass(B, B)) # True
print(issubclass(A, B)) # False
18. iter(): 生成迭代器。如果传递了第二个参数,则object对象必须是一个可调用的对象(实现了__call__方法)。
list(): 将可迭代对象转化为列表。
# iter()
# 生成迭代器
# iter(object, sentinel)
# 如果传递了第二个参数,则参数 object 必须是一个可调用的对象(如,函数),此时,iter 创建了一个迭代器对象,每次调用这个迭代器对象的__next__()方法时,都会调用 object。
a = [1, 2] # <class 'list_iterator'>
b = (1, 2) # <class 'tuple_iterator'>
c = {"name": "maxin", "age": 23} # <class 'dict_keyiterator'>
d = set(a) # <class 'set_iterator'>
# res = iter(a)
# res = iter(b)
# res = iter(c)
# res = iter(d)
# print(type(res))
# for item in res:
# print(item)
def e():
pass
res = iter(e, "test") # <callable_iterator object at 0x0000026CCBB2E0B8>
print(res)
for i in res:
print(i)
19. memoryview(): 返回给定参数的内存查看对象(Momory view)。所谓内存查看对象,是指对支持缓冲区协议的数据进行包装,在不需要复制对象基础上允许Python代码访问。
# memoryview()
# 返回给定参数的内存查看对象(Momory view)。
# 所谓内存查看对象,是指对支持缓冲区协议的数据进行包装,在不需要复制对象基础上允许Python代码访问。
v = memoryview(bytearray("abcdef", "utf-8"))
print(v[0])
print(v[-1])
print(v[1:4])
print(type(v)) # <class 'memoryview'>
print(v[0:3].tobytes()) # b'abc'
20. property(): 在新式类(继承自object)中返回属性值。
21.range(): python3中range()返回的是一个整数序列的对象,而并非列表,但可通过list函数进行转换。
round(): 对round函数进行近似取值,保留几位小数。但是,这个函数也有一些坑。
# range()
# 可创建一个整数序列对象,一般用在 for 循环中。
print(type(range(10)))
# Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step.
help(range)
range(100, 19, -5)
22. slice(): 实现切片对象,主要用在切片操作函数里的传递参数
super():子类调用父类的构造函数(减少代码量,方便修改)
# slice()
# class slice(start, stop, step)
# 实现切片对象,主要用在切片操作函数里的参数传递
myslice = slice(1, 3, 1)
print(type(myslice)) # <class 'slice'>
arr = range(10)
print(list(arr)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
new_arr = arr[myslice]
print(type(new_arr)) # <class 'range'>
print(list(new_arr)) # [1, 2]
# super()
# diao用继承的父类的构造函数
class Person(object):
def __init__(self, name, sex, age):
self.name = name
self.sex = sex
self.age = age
class Man(Person):
def __init__(self, name, sex, age, character):
super(Man, self).__init__(name, sex, age)
self.character = character
23. zip(): 用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。我们可以使用 list() 转换来输出列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
# zip()
# zip(iterable)
# 将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象
a = [1, 2, 3]
b = [4, 5, 6]
c = [4, 5, 6, 7, 8]
zipped = zip(a, b)
print(zipped) # <zip object at 0x0000020DE6FD1088>
print(list(zipped)) # [(1, 4), (2, 5), (3, 6)]
print(list(zip(a, c))) # [(1, 4), (2, 5), (3, 6)]
a1, a2 = zip(*zip(a, b)) # 解压之后返回的是元组tuple
print(a1)
print(a2)
24. __import__(): 用于动态加载类和函数 。如果一个模块经常变化就可以使用 __import__() 来动态载入。
# atest.py
class Testclass(object):
def func(self):
print 123
# test.py
a=__import__('atest') #等于 import atest
b=getattr(a,'Testclass') #根据类名获得类对象
c=b() #实例化
c.func()