Python 中每个内置函数的简明解释

categories: [编程,python]  
函数名 函数名 函数名 函数名 函数名
abs aiter all any ascii
bin bool bytearray bytes callable
chr classmethod compile complex delattr
dict dir divmod enumerate eval
exec exit filter float format
getattr globals hasattr hash help
hex id input int isinstance
issubclass iter next len list
locals map max min oct
open ord pow print property
quit range repr reversed round
set sorted str sum tuple
type zip

abs()

负数变为正数。正数仍然是正数。

print(abs(-10))  # 10
print(abs(10))   # 10

image-20240722154731468

aiter() 和 anext()

aiter 是 async iter 的缩写,anext 是 async next 的缩写

aiter() 是 iter() 的异步等价函数

anext() 是 next() 的异步等价函数

aiter() 调用对象的 aiter() 方法,而 anext() 调用对象的 anext() 方法。

all()

接收某些序列,如列表、元组等

如果序列中的所有内容都为 True,则返回 True

如果序列中至少有一个元素为 False,则返回 False

print(all([True, True, True]))    # True
print(all([True, False, False]))   # False

image-20240722154748052

any()

接收某些序列,如列表、元组等

如果序列中至少有一个元素为 True,则返回 True

如果序列中的所有内容均为 False,则返回 False

print(any([False, False, False]))   # False
print(any([True, False, False]))    # True

image-20240722154808168

ascii()

将字符转换为统一码

x = ascii("Symbols: δ Ω α β")
print(x) # "'Symbols: \\u03b4 \\u03a9 \\u03b1 \\u03b2'"

image-20240722154827924

bin()

将数字转换为二进制

print(bin(1))    # 0b10
print(bin(2))    # 0b100
print(bin(10))    # 0b1010

image-20240722153913684

bool()

将对象转换为 True 或 False

  • 将 0 或空列表/空元组 变为 False
  • 将非零或非空序列 变为 True
print(bool(0))    # False
print(bool(''))    # False
print(bool([]))   # False
print(bool(()))   # False

print(bool(10))  # True
print(bool([1]))  # True
print(bool('x'))  # True

image-20240722153410892

bytearray()

将对象转换为可变字节数组

print(bytearray(0))    # bytearray(b'')
print(bytearray(1))    # bytearray(b'\x00')
print(bytearray(10))    

image-20240722153808336

bytes()

将对象转换为不可变的字节

print(bytes(0))    # b''
print(bytes(1))    # b'\x00'
print(bytes(10))   

image-20240722154655845

callable()

如果对象是可调用的,则返回 True,否则返回 False。如果对象是一个函数,或者实现了其 call 方法,则该对象是可调用的。

a = 1

def b():
    print()

print(callable(a))    # False
print(callable(b))    # True

image-20240722154640269

chr()

character的简称。每个字符都有一定的统一编码。

chr(unicode) 输入 unicode 数字并返回字符。

print(chr(65))    # A
print(chr(66))    # B

print(chr(97))    # a
print(chr(98))    # b

print(chr(49))   # 1
print(chr(50))   # 2

image-20240722154611053

classmethod()

我不是很懂这个内置函数,也难理解它,平常用它较少甚至没用过。

class Dog:
    breeds = ['german shepherd', 'mongrel', 'retriver']

    @classmethod
    def get_breeds(cls):
        return cls.breeds

print(Dog.get_breeds())
# ['german shepherd', 'mongrel', 'retriver']

compile()

接收代表 Python 代码的字符串,并将其编译以便稍后执行。

code = 'a = 4\nb = 5\nprint(a + b)'
code = compile(code, 'test.py', 'exec')
<code object <module> at 0x000001B5E92CBC90, file "test.py", line 1>
exec(code)
# 9

image-20240722155519274

complex()

用它来创建复数

x = complex(1, 2)

print(x)  # (1+2j)

image-20240722155609656

delattr()

删除对象的一个属性。

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

dog = Dog('gogo', 2)

print(dog.__dict__) # {'name': 'gogo', 'age': 2}
delattr(dog, 'age')   # 删除 'age' 属性

print(dog.__dict__)   # {'name': 'gogo'}

dict()

创建字典

d = dict(a=4, b=5, c=6)

print(d)

# {'a': 4, 'b': 5, 'c': 6}

image-20240722161621599

dir()

在python里,一切都是对象。

dir()以 list[str] 形式返回对象的所有属性/方法

n = 1

print(dir(n))

def a():
	print()

print(dir(a))
	

image-20240722161822338

divmod()

地板除与取模

quotient, remainder = divmod(59, 10)

print(quotient)    # 5
print(remainder)   # 9

image-20240722162142296

enumerate()

可以代替for循环

生成某个序列/迭代器的索引和值

letters = ['a', 'b', 'c']

for index, letter in enumerate(letters):
    print(f'{index=} {letter=}')

'''
index=0 letter='a'
index=1 letter='b'
index=2 letter='c'
'''

image-20240722162350283

eval()

接收字符串,并以 Python 代码形式对字符串进行求值,然后返回求得的值。

print(eval('1 + 10 + 100 + 1000 + 10000')) # 11111

image-20240722162444116

exec()

接收字符串,以 Python 代码执行该字符串,返回 None。

x = 5

exec('x = 100')

print(x) # 100

image-20240722162522176

exit()

完全停止 Python 程序。

x = 10
print(x + 1)

exit()  # Python程序在这里退出。不会运行后续的代码。

print(x + 2)

image-20240722162709833

filter()

filter(condition,iterable)接收一个条件condition和一个interable。

它只输出满足条件的元素。

下面是一个只保留 [1,2,3,4,5,6,7] 中奇数的例子

mylist = [1, 2, 3, 4, 5, 6, 7]

def condition(n: int) -> bool:
    return n % 2 == 1

for i in filter(condition, mylist):
    print(i, end=' ')

image-20240722162945244

float()

将对象转换为浮点数。

n = float('3.14')

print(n) # 3.14

format()

根据对象的 format 方法,以某种方式格式化某个对象。

n = 20

x = format(n, 'b')

print(x)  # 10100

getattr()

访问对象的属性

class Person:
    def __init__(self, name):
        self.name = name

person = Person('Hanmeimei')

print(person.name)  

globals()

返回包含所有全局变量的字典

a = 4
b = 5

print(globals())

我们也可以使用 globals() 动态设置变量

globals()['a'] = 100

print(a) # 100

hasattr()

如果对象有属性,则返回 True,否则返回 False

class Person:
    def __init__(self, name):
        self.name = name

person = Person('Hanmeimei')

print(hasattr(person, 'name'))      # True
print(hasattr(person, 'nickname'))  # False

hash()

返回不可变对象的哈希值。 hash() 对可变对象不起作用,因此可用于检查对象是否可变。

print(hash(5))        # 5
print(hash(100))      # 100
print(hash('apple'))  # 6125743690088875441

help()

打印我们传入的对象的文档。

help(print)

'''
Help on built-in function print in module builtins:

print(*args, sep=' ', end='\n', file=None, flush=False)
    Prints the values to a stream, or to sys.stdout by default.

    sep
      string inserted between values, default a space.
    end
      string appended after the last value, default a newline.
      ...
'''

hex()

将数字转换为十六进制

print(hex(8))    # 0x8
print(hex(9))    # 0x9

print(hex(10))   # 0xa
print(hex(11))   # 0xb

print(hex(15))   # 0xf
print(hex(16))   # 0x10

print(hex(17))   # 0x11
print(hex(18))   # 0x12

对于不熟悉十六进制的人来说,十六进制就是以 16 为基数计数。基本上就像我们有 16 个手指而不是 10 个手指一样。

id()

所有 Python 对象都有自己唯一的 id。

a = 'HanMeimei'
b = 'LiMing'

print(id(a))    # 1906439904176
print(id(b))    # 1906439911152

input()

允许用户向我们的 Python 程序输入输入内容

name = input('enter your name >>> ')

print('your name is', name)

# enter your name >>> HanMeimei
# your name is HanMeimei

有时候在打包程序时用到。

int()

将对象转换为整数

n = int('100')

print(n)      # 100
print(n + 1)  # 101

isinstance()

isinstance(o, type) 检查 o 是否是 type 的实例

a = 'apple'

print(isinstance(a, str))  # True

print(isinstance(a, int))  # False

这也适用于类:

class Animal:
    ...

class Dog(Animal):
    ...

dog = Dog()

print(isinstance(dog, Dog))      # True

print(isinstance(dog, Animal))   # True

issubclass()

检查某个类是否为子类

class Animal:
    ...

class Dog(Animal):
    ...

print(issubclass(Dog, Animal))

iter() 和 next()

iter(mylist) 返回一个迭代器对象。

next(iterator_object) 返回迭代器对象中的下一个元素。

fruits = ['apple', 'orange', 'pear']

for fruit in fruits:
    print(fruit)

# apple orange pear
fruits = ['apple', 'orange', 'pear']

iterator = iter(fruits)

a = next(iterator)
print(a)  # apple

b = next(iterator)
print(b)  # orange

c = next(iterator)
print(c)  # pear

iter() 和 next() 可以让我们在迭代过程中进行更大程度的控制,因此非常有用。

len()

len(object) 查找对象的长度。

字符串长度:

mystring = 'applepie'

print(len(mystring)) # 8

列表长度:

mylist = [1, 2, 3, 4, 5]

print(len(mylist))  # 5

字典长度:

mydict = {'apple':1, 'orange':2}

print(len(mydict))  # 2

list()

列表数据类型。还可将其他可迭代数据类型转换为列表。

s = 'apple'

ls = list(s)

print(ls)  # ['a', 'p', 'p', 'l', 'e']

locals()

返回包含本地变量的字典。

a = 1
b = 2

def test():
    c = 3
    d = 4
    print(locals())

test()

# {'c': 3, 'd': 4}

map()

map(func, iterable) 将 func 应用于 iterable 中的每个元素

def add10(n :int) -> int:
    return n + 10

numbers = [1, 2, 3, 4, 5]

new = map(add10, numbers)
new = list(new)

print(new)    # [11, 12, 13, 14, 15]

max()

查找序列中的最大值

numbers = [1, 5, 3, 9, 2]

n = max(numbers)

print(n) # 9

min()

查找序列中的最小值

numbers = [1, 5, 3, 9, 2]

n = min(numbers)

print(n) # 1

oct()

oct(n) 输入一个数字,并返回其八进制值。

print(oct(6))   # 0o6
print(oct(7))   # 0o7 
print(oct(8))   # 0o10
print(oct(9))   # 0o11
print(oct(10))  # 0o12

open()

用于打开文件进行读写

with open('fruits.txt') as f:
    # read text inside fruits.txt
    text = f.read()

print(text)

ord()

ord(chr) 返回字符 chr 的顺序

print(ord('A'))  # 65
print(ord('B'))  # 66

print(ord('a'))  # 97
print(ord('b'))  # 98
print(ord('c'))  # 99

pow()

pow(a,b)接收 2 个数字,并返回 a 到 b 的幂次

print(pow(2, 2))  # 4
print(pow(2, 3))  # 8
print(pow(2, 4))  # 16

print()

将内容打印到终端

property()

在类中用于将属性转化为属性的装饰器

class Dog:
    def __init__(self, name):
        self.__name = name

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, new_name):
        self.__name = new_name

dog = Dog('name')

我们可以直接调用 dog.name 来获取它的名字

print(dog.name)    # rocky

由于我们定义了一个 setter 方法,因此也可以直接更改 dog.name

dog.name = 'fifi'

print(dog.name)    # fifi

quit()

和 exit() 一样,它会完全停止 Python 程序。

range()

经常在循环语句中使用。

for i in range(5):
    print(i)

# 0 1 2 3 4
for i in range(2, 6):
    print(i)

# 2 3 4 5
for i in range(3, 10, 3):
    print(i)

# 3 6 9

repr()

返回表示对象的字符串。常用于开发和调试。

from datetime import datetime

dt = datetime(2024, 7, 25)

print(str(dt))   # 2024-07-25 00:00:00

print(repr(dt))  # datetime.datetime(2024, 7, 25, 0, 0)

reversed()

字面意思,反转。

ls = [1, 2, 3, 4, 5]

ls = list(reversed(ls))

print(ls)   # [5, 4, 3, 2, 1]

round()

将数字舍入到最接近的小数点。

pi = 3.14159265

print(round(pi))      # 3
print(round(pi, 2))   # 3.14
print(round(pi, 5))   # 3.14159

也可用于将数字四舍五入到最接近的十位百位千位。

num = 987654321

print(round(num))      # 987654321
print(round(num, -1))  # 987654320
print(round(num, -2))  # 987654300
print(round(num, -3))  # 987654000

set()

集合

  • 不能包含重复值
  • 让我们可以在 O(1) 时间内检查元素是否在内部
s = set()

s.add(1)
s.add(2)
s.add(3)

print(s)  # {1, 2, 3}

集合可以有效减少某些循环的处理时间

sorted()

返回序列(如列表)的排序副本

ls = [1, 5, 3, 4, 2]

new = sorted(ls)

print(new)
# [1, 2, 3, 4, 5]

str()

内置字符串类型。还可将其他对象转换为字符串。

a = 5
b = 3.14

print(str(a))    # 5
print(str(b))    # 3.14

new = str(a) + str(b)

print(new)       # 53.14

sum()

sum(sequence) 将 sequence 中的元素相加,并返回总和。

numbers = [1, 2, 3, 4, 5]

total = sum(numbers)

print(total)    # 15

tuple()

内置的元组数据类型。还可将对象转换为元组。

对于不熟悉的人来说,元组只是不可变的列表,创建后不能更改。优点:元组可以是 dict key,也可以添加到集合中。

ls = [1, 2, 3]

t = tuple(ls)

print(t)    # (1, 2, 3)

type()

type(object) 返回object的类型。

print(type(1))        # <class 'int'>

print(type(3.14))     # <class 'float'>

print(type('apple'))  # <class 'str'>

print(type([]))       # <class 'list'>

print(type({}))       # <class 'dict'>

zip()

允许我们同时遍历多个序列

fruits = ['apple', 'orange', 'pear']
prices = [4, 5, 6]

for fruit, prices in zip(fruits, prices):
    print(fruit, price)

# apple 4
# orange 5
# pear 6

我们可以在 zip() 中传递任意数量的参数

a = [1, 2, 3]
b = [2, 4, 6]
c = [3, 6, 9]
d = [4, 8, 12]

for i,j,k,l in zip(a, b, c, d):
    print(i, j, k, l)

# 1 2 3 4
# 2 4 6 8
# 3 6 9 12