# Python的内置方法
Built-in Functions
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()
内置参数详解
https://docs.python.org/3/library/functions.html?highlight=built#ascii
1-1 all ()
>>> all ([0,-5,3])
False
>>> all ([1,-5,3])
True
>>>
all (iterable)
Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:
def all (iterable):
for element in iterable:
if not element:
return False
return True
1-2 any ()
>>> any ([0,-5,3])
True
>>> any ([1,-5,3])
True
>>>
any (iterable)
Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:
def any (iterable):
for element in iterable:
if element:
return True
return False
1-3 ascii ()
>>> ascii ([1,2])
'[1, 2]'
>>> ascii ([1,2,"开挂"])
"[1, 2, '\\u5f00\\u6302']"
>>> a = ascii ([1,2,"开挂"])
>>> type(a)
<class 'str'>
# 把内存的数据对象变成可打印的字符串的形式,所以这个函数并没有什么用
ascii (object)
As repr (), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by repr () using \x, \u or \U escapes.
This generates a string similar to that returned by repr () in Python 2.
2-1 bin ()
>>> bin (1)
'0b1'
>>> bin (2)
'0b10'
>>> bin (4)
'0b100'
>>> bin (8)
'0b1000'
>>> bin (255)
'0b11111111'
>>>
# bin 就是十进制转二进制,b代表二进制;将数字转为二进制
bin (x)
Convert an integer number to a binary string prefixed with “0b”.
The result is a valid Python expression.
If x is not a Python int object, it has to define an __index__ () method that returns an integer.
Some examples:
>>> bin (3)
'0b11'
>>> bin (-10)
'-0b1010'
If prefix “0b” is desired or not, you can use either of the following ways.
>>> format (14, '#b'), format (14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
See also format () for more information.
2-2 bool()
>>> bool(0)
False
>>> bool(1)
True
>>> bool([1])
True
>>> bool([])
False
>>>
class bool([x])
Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure.
If x is false or omitted, this returns False; otherwise it returns True.
The bool class is a subclass of int (see Numeric Types — int, float, complex).
It cannot be subclassed further. Its only instances are False and True (see Boolean Values).
Changed in version 3.7: x is now a positional-only parameter.
2-3 bytearray()
# bytearray 字节数组
>>> a = bytes("abcde",encoding="utf-8")
>>> a
b'abcde'
>>> a.capitalize()
b'Abcde'
>>> a
b'abcde'
# 字符串不可以修改,二进制的字节格式也不可以修改
# 列表可以修改,但是字符串不可以,如果修改字符串需要生成一个新的
class bytearray([source[, encoding[, errors]]])
Return a new array of bytes. The bytearray class is a mutable sequence of integers in the range 0 <= x < 256.
It has most of the usual methods of mutable sequences , described in Mutable Sequence Types , as well as most methods that the bytes type has , see Bytes and Bytearray Operations .
The optional source parameter can be used to initialize the array in a few different ways :
If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
If it is an integer, the array will have that size and will be initialized with null bytes.
If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.
Without an argument, an array of size 0 is created.
See also Binary Sequence Types — bytes, bytearray, memoryview and Bytearray Objects.
2-3-1
# bytearray 就是可修改的二进制字节模式
>>> b = bytearray("abcde",encoding="utf-8")
>>> b
bytearray(b'abcde')
>>> b[0]
97
# 打印的是 "a"的 ascii 码,a的ascii码 对应的就是 97
>>> b[1]
98
>>> b[2]
99
>>>
2-3-2
# 现在给 b 重新赋值
>>> b[1] = 'B'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
>>>
# 赋值必须是 ascii 码格式才可以
>>> b[1] = 100
>>> b
bytearray(b'adcde')
>>> b[1] = 50
>>> b
bytearray(b'a2cde')
>>>
# 所以 bytearray 相当于把 二进制数 变成了数组,一个列表的形式,并可以对其进行修改
3-1 callable ()
>>> callable ([])
False
>>> def sayhi ():pass
...
>>> callable (sayhi)
True
>>>
callable (object)
Return True if the object argument appears callable , False if not.
If this returns True, it is still possible that a call fails, but if it is False, calling object will never succeed.
Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a __call__ () method.
New in version 3.2: This function was first removed in Python 3.0 and then brought back in Python 3.2.
3-2 chr ()
# 返回 ascii 码的对应表
>>> chr (97)
'a'
>>> chr (98)
'b'
>>>
# 把数字对应的 ascii 码,翻译过来
chr (i)
Return the string representing a character whose Unicode code point is the integer i.
For example, chr (97) returns the string 'a', while chr (8364) returns the string '€'.
This is the inverse of ord ().
The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16).
ValueError will be raised if i is outside that range .
3-3 ord ()
# 直接输入字符,返回 ascii 码;和 chr()是对应相反的
# 所以必须写 ascii 码的字符
>>> ord ('d')
100
>>> ord ('b')
98
>>>
ord (c)
Given a string representing one Unicode character, return an integer representing the Unicode code point of that character.
For example, ord ('a') returns the integer 97 and ord ('€') (Euro sign) returns 8364.
This is the inverse of chr ().
3-4 classmethod()
# 有些像装饰器,这是一个类方法,以后会提及
@classmethod
Transform a method into a class method.
A class method receives the class as implicit first argument, just like an instance method receives the instance.
To declare a class method, use this idiom:
class C:
@classmethod
def f(cls, arg1, arg2, ...): ...
The @classmethod form is a function decorator – see Function definitions for details.
A class method can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.
Class methods are different than C++ or Java static methods. If you want those, see staticmethod() in this section. For more information on class methods, see The standard type hierarchy.
Changed in version 3.9: Class methods can now wrap other descriptors such as property().
3-5 compile ()
# 几乎用不到,是底层将代码用于编译的过程
>>> code = "for i in range(10):print(i)"
>>> code
'for i in range(10):print(i)'
>>> compile (code,'','exec')
<code object <module> at 0x000001EAA35D1780, file "", line 1>
>>>
# 变成了一个内存中的 pyobject 数据对象
# exec 可以把字符串执行为代码
3-5-1
>>> c = compile (code,'','exec')
>>> exec (c)
0
1
2
3
4
5
6
7
8
9
>>>
# 所以 compile 就是这个意思
3-5-2
>>> code = "1+3/2*6"
>>> c = compile (code,'','eval')
>>> c
<code object <module> at 0x000001EAA35D1B70, file "", line 1>
>>> eval (c)
10.0
>>> eval (code)
10.0
>>>
# eval 不需要编译,本来就可以执行 code
3-5-3
code = '''
def fib(max):
n,a,b = 0,0,1
while n < max:
# print(b)
yield b
a, b = b, a + b
n = n + 1
return 'done'
g=fib(6)
while True:
try:
x=next(g)
print('g:', x)
except StopIteration as e:
print('Generator returnvalue:', e.value)
break
'''
py_obj = compile (code,"err.log","exec")
# err.log 那地方是文件名,编译出错时,会把错误打印到里面,但实践证明并不好使
exec (py_obj)
--->
g: 1
g: 1
g: 2
g: 3
g: 5
g: 8
Generator returnvalue: done
# 所以,可以把文件中的代码全读出来,存成变量,通过编译的形式,把字符串变成执行代码
# 相当于 import 这个模块并执行
3-5-4
# 其实直接 exec 就可以执行,并不需要 compile,忘记它吧
code = '''
def fib(max):
n,a,b = 0,0,1
while n < max:
# print(b)
yield b
a, b = b, a + b
n = n + 1
return 'done'
g=fib(6)
while True:
try:
x=next(g)
print('g:', x)
except StopIteration as e:
print('Generator returnvalue:', e.value)
break
'''
exec (code)
--->
g: 1
g: 1
g: 2
g: 3
g: 5
g: 8
Generator returnvalue: done
3-6 complex()
# 返回复数
4-1 delattr ()
delattr (object, name)
This is a relative of setattr ().
The arguments are an object and a string.
The string must be the name of one of the object’s attributes.
The function deletes the named attribute, provided the object allows it.
For example, delattr (x, 'foobar') is equivalent to del x.foobar.
class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
Create a new dictionary.
The dict object is the dictionary class.
See dict and Mapping Types — dict for documentation about this class.
For other containers see the built-in list, set, and tuple classes, as well as the collections module.
4-1-2
>>> {}
{}
>>> dict()
{}
# 这两种都是生成默认字典的方式
4-2 dir ()
# 比如 有一个字典,现在想查看字典中都有什么方法
>>> a = {}
>>> dir (a)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__',
'__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__',
'__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items',
'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>>
# 两个下划线 __ 的是内部方法,除了__next__(),一般不能用
4-3 divmod ()
# 商除,然后返回余数
>>> divmod (5,2)
(2, 1)
>>> divmod (5,3)
(1, 2)
>>>
# 前面的是商,后面的是余数
5-1 enumerate ()
5-2 eval ()
>>> x=1
>>> eval ('x+1')
2
# 将字符串变成字典,做的是一些数字上的简单计算
5-3 exec ()
6-1 filter ()
# 在了解 filter() 之前,需要先知道匿名函数
6-1-2 匿名函数
def sayhi(n):
print (n)
sayhi(3)
# 如果这个方法,整个程序只使用一次;可能没有必要单独写一个函数,因为函数的一个作用就是重复使用
# 所以这种情况,就可以写一个匿名函数,用完就释放
6-1-2-1
>>> (lambda n: print (n))(5)
5
# 匿名函数还是很重要的
# 但是这样不是很好理解,所以可以给它进行赋值
6-1-2-2
calc = lambda n: print (n)
calc(5)
--->
5
# 这个和 6-1-2 中的函数是一模一样的
33:34
6-1-3
def sayhi(n):
print (n)
for i in range (n):
print (i)
sayhi(3)
# 匿名函数只能处理三元运算
cala = lambda n:for i in range (n): print (i)
calc(5)
# 这种里面有 for 循环的,匿名函数是无法处理的
6-1-3-2
calc = lambda n:n**n
calc(5)
# 匿名函数可以处理这种
6-1-3-3
# 三元运算,比如
calc = lambda n:3 if n<4 else n
print (calc(2))
--->3
# 所以匿名函数单独使用的情况不多,需要结合起来使用,这时就需要 filter 了
6-1-4
# filter 过滤一组数据,得到想要的结果
# 从 0 到 10,过滤出 大于 5 的
>>> filter (lambda n:n>5, range (10))
< filter object at 0x000001EAA3665DC8>
>>>
# 在 3.0 中,变成迭代器了,所以需要循环打印
>>> res = filter (lambda n:n>5, range (10))
>>> for i in res:
... print (i)
...
6
7
8
9
>>>
7-1 map ()
# 除了 filter(),匿名函数也可以和 map() 函数结合使用
>>> res = map (lambda n:n*n, range (10))
>>> for i in res:
... print (i)
...
0
1
4
9
16
25
36
49
64
81
# filter 是把过滤合格的结果打印出来
# map 是对传入的每一个值进行处理,处理后返回并覆盖原结果
>>> res = map (lambda n:n*2, range (10)) # 相当于 [i*2 for i in range(10)]
>>> for i in res:
... print (i)
...
0
2
4
6
8
10
12
14
16
18
>>>
7-1-2
# 列表生成式也可以用匿名函数
res = [lambda i:i*2 for i in range (10)]
for i in res:
print (i)
7-2 reduce()
# reduce 函数在 python2 中有,在 python3 中需要 import 导入,将 reduce 内置方法移动到 标准库中
import functools
res = functools.reduce(lambda x,y:x+y, range (10))
print (res)
--->
45
# 累加,从 0 加到 9
7-2-1
# 如果换成乘法,就是 阶乘
import functools
res = functools.reduce(lambda x,y:x*y, range (1,10))
print (res)
--->
362880
7-3 frozenset()
a = frozenset([1,4,333,212,33,33,12,4])
# 不可变集合,就像元组一样,不可变
8-1 getattr ()
# 面向对象时会提到
8-2 globals ()
# globals()返回当前程序所有变量的 key-value 的格式,变量是 key,变量值为 value
>>> print ( globals ())
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>……}
>>>
# 可以用来判断变量是否存在
globals ()
Return a dictionary representing the current global symbol table.
This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).
9-1 hash ()
# 哈希,中文名称为散列
# 如果数据是有关系的,且是有序的,算法就可以上场了
# 高效查询数据的前提是,通过数字变成有规律的映射关系,python 内部的寻找数据的原理就是这样的
# 这种映射关系,就叫哈希;映射关系是固定的,比如 张三 对应 数字 1;如果张三被删除,数字1 也是被删除的
# 映射关系必须是固定的
# 比较两个文件的不同,每个文件都会生成一个 MD5,通过对比 MD5 判断文件是否相同
# MD5 本质上 也是 哈希
>>> hash (1)
1
>>> hash (1233431)
1233431
>>> hash ('alex')
-7932606926095588202
>>> hash ('json')
-4788005738502895980
>>>
hash (object)
Return the hash value of the object (if it has one). Hash values are integers.
They are used to quickly compare dictionary keys during a dictionary lookup.
Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).
Note
For objects with custom __hash__ () methods, note that hash () truncates the return value based on the bit width of the host machine. See __hash__ () for details.
1-1 hex ()
# 转成 16 进制
>>> hex (10)
'0xa'
>>> hex (255)
'0xff'
>>> hex (15)
'0xf'
hex (x)
Convert an integer number to a lowercase hexadecimal string prefixed with “0x”. If x is not a Python int object, it has to define an __index__ () method that returns an integer. Some examples:
>>> hex (255)
'0xff'
>>> hex (-42)
'-0x2a'
If you want to convert an integer number to an uppercase or lower hexadecimal string with prefix or not, you can use either of the following ways:
>>> '%#x' % 255, '%x' % 255, '%X' % 255
('0xff', 'ff', 'FF')
>>> format (255, '#x'), format (255, 'x'), format (255, 'X')
('0xff', 'ff', 'FF')
>>> f'{255:#x}', f'{255:x}', f'{255:X}'
('0xff', 'ff', 'FF')
See also format () for more information.
See also int() for converting a hexadecimal string to an integer using a base of 16.
Note
To obtain a hexadecimal string representation for a float, use the float.hex() method.
2-1 locals ()
locals ()
Update and return a dictionary representing the current local symbol table.
Free variables are returned by locals () when it is called in function blocks, but not in class blocks.
Note that at the module level, locals () and globals () are the same dictionary.
Note
The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
2-1-1
def test():
local_var = 333
print ( globals ())
print ( globals ().get('local_var'))
--->
>>> print ( globals ())
{'__name__': '__main__', '__doc__': None, '__package__': None ……}
None
# 打印结果中,没有 local_var 这个变量,因为 globals 只打印全局变量,不打印局部变量
2-1-2
# 如果在函数内部打印 globals() 会怎样
def test():
local_var = 333
print ( globals ())
print ( globals ().get('local_var'))
test()
--->
{'__name__': '__main__', '__doc__': None, '__package__': None ……}
None
# 打印结果同样没有 local_var
2-1-3
def test():
local_var = 333
print (( locals ()))
test()
--->
{'local_var': 333}
# 只有 locals() 可以打印局部变量
3-1 object()
# 在 python 中,一切皆对象
# 对象,世界万物皆为对象
# 每一个对象,都有属性,比如 年龄 名字 身高 颜色 等;并且也有很多功能,可以通过 点 调用
# 比如 对象 person,调用功能 sleep,就是 person.sleep
# 字符串、列表 都是对象,比如 list.append()
# 所以 python 中,一切皆对象
# 有对象,就肯定有属性,属性就是通过 点 调用;比如 list.copy(self)
3-2 oct ()
# 十六进制是 hex(),转八进制就是 oct()
>>> oct (1)
'0o1'
>>> oct (5)
'0o5'
>>> oct (8)
'0o10'
>>> oct (9)
'0o11'
>>> oct (15)
'0o17'
>>> oct (16)
'0o20'
# 这就是八进制,不过并没有什么用
3-3 pow ()
>>> pow (3,5)
243
>>> pow (3,3)
27
# 次幂计算
4-1 repr ()
# 和 ascii() 函数一样
>>> c
<code object <module> at 0x000001EAA35D1B70, file "", line 1>
>>> repr (c)
'<code object <module> at 0x000001EAA35D1B70, file "", line 1>'
# 转成 字符串了;其实并没有什么用
4-2 reversed ()
# 和列表中的 reverse()是一样的
4-3 round ()
>>> round (1.3342)
1
>>> round (1.3342,2) # 保留小数点后两位
1.33
5-1 slice()
>>> slice(2,5)
slice(2, 5, None)
>>> d = range (20)
>>> d[slice(2,5)]
range (2, 5)
>>> d[2:5]
range (2, 5)
# slice()切片,d[slice(2,5)] 与 d[2:5] 是一样的;所以没什么用
5-2 sorted ()
a = {6:2,8:0,1:4,-5:6,99:11,4:22}
print (a)
--->
{6: 2, 8: 0, 1: 4, -5: 6, 99: 11, 4: 22}
# 结果是无序的,现在将其进行排序
>>> print ( sorted (a))
[-5, 1, 4, 6, 8, 99]
# 这个只是对 键值 进行排序,如何对 整个字典 进行排序?
5-2-2
>>> print ( sorted (a.items()))
[(-5, 6), (1, 4), (4, 22), (6, 2), (8, 0), (99, 11)]
# 排序后,变成一个列表,不能指望排序后还是一个字典
5-2-3
# 也可以 按 value 排序
>>> a
{6: 2, 8: 0, 1: 4, -5: 6, 99: 11, 4: 22}
>>> print ( sorted (a.items(),key=lambda x:x[1]))
[(8, 0), (6, 2), (1, 4), (-5, 6), (99, 11), (4, 22)]
>>>
# x 相当于 每一个元素 x[1] 指 第一个元素
6-1 type()
# class type() 是所有数据类型的起源
7-1 vars ()
# 返回一个对象的属性名,一般用不到
8-1 zip ()
>>> a = [1,2,3,4]
>>> b = ['a','b','c','d']
# 现在要把 a 和 b 组合起来
>>> print ( zip (a,b))
< zip object at 0x000001EAA365A088>
# 3.0 中变成了 迭代器, 2.0 中可以直接看结果
>>> for i in zip (a,b):
... print (i)
...
(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')
>>>
8-1-2
# 如果, a 多了 b 少了,怎么办?
# 按最少的来
>>> a = [1,2,3,4,5,6]
>>> b = ['a','b','c','d']
>>> for i in zip (a,b):
... print (i)
...
(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')
>>>
9-1 __import__ ()
# 如果只知道字符串,可以用 __import__()导入
__import__ ('decorator')