「Python系列」Python 内置函数

本文涉及的产品
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
可观测可视化 Grafana 版,10个用户账号 1个月
简介: Python 提供了许多内置函数,这些函数在 Python 解释器中直接可用,无需导入任何模块。

一、Python内置函数

Python 提供了许多内置函数,这些函数在 Python 解释器中直接可用,无需导入任何模块。以下是一些常用的 Python 内置函数及其详细案例代码:

1. abs(x)

返回数字的绝对值。

print(abs(-7))  # 输出: 7

2. all(iterable)

如果可迭代对象的所有元素都为真(或可迭代对象为空),则返回 True。

print(all([1, 2, 3, 4]))  # 输出: True
print(all([1, 2, 0, 4]))  # 输出: False

3. any(iterable)

如果可迭代对象中有任何元素为真,则返回 True。

print(any([0, 0, 0]))  # 输出: False
print(any([0, 0, 1]))  # 输出: True

4. ascii(object)

返回表示对象的可打印 ASCII 字符串。

print(ascii('你好'))  # 输出: "'\\u4f60\\u597d'"

5. bin(x)

返回整数的二进制表示。

print(bin(10))  # 输出: '0b1010'

6. bool(x)

将给定值转换为布尔值(True 或 False)。

print(bool(0))  # 输出: False
print(bool(1))  # 输出: True
print(bool(''))  # 输出: False
print(bool('Hello'))  # 输出: True

7. breakpoint()

在交互式解释器中,此函数是内置函数 pdb.set_trace() 的别名。

def my_function():
   for i in range(5):
       print(i)
       if i == 2:
           breakpoint()
my_function()

8. bytearray(source[, encoding[, errors]])

返回一个新的“bytearray”对象,它是一个可变(mutable)的序列类型,其元素是 0 <= x < 256 的整数。

ba = bytearray(b'hello')
print(ba)  # 输出: bytearray(b'hello')

9. bytes(source[, encoding[, errors]])

返回一个新的“bytes”对象,它是不可变的,并且其元素是 0 <= x < 256 的整数。

b = bytes('hello', 'utf-8')
print(b)  # 输出: b'hello'

10. callable(object)

返回 object 是否是可调用的(即,是否定义了 __call__() 方法)。

def hello():
    pass

print(callable(hello))  # 输出: True
print(callable(123))  # 输出: False

11. chr(i)

返回整数 i 对应的 ASCII 字符。

print(chr(65))  # 输出: 'A'

12. classmethod(function)

将方法转换为类方法。

class MyClass:
    @classmethod
    def my_method(cls, arg1, arg2):
        print(cls, arg1, arg2)

MyClass.my_method('hello', 'world')  # 输出: <class '__main__.MyClass'> hello world

13. compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

编译源代码字符串,返回代码对象。

code = compile('print("Hello, world!")', '<string>', 'exec')
exec(code)  # 输出: Hello, world!

14. complex(real[, imag])

返回一个新的复数,实部为 real,虚部为 imag。

c = complex(4, 3)
print(c)  # 输出: (4+3j)

15. delattr(object, name)

删除对象的属性。

delattr 是 Python 的一个内置函数,用于删除对象的属性。这个函数的语法是 delattr(object, name),其中 object 是要删除属性的对象,name 是要删除的属性的名称(作为字符串提供)。

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

# 创建一个 Person 对象
p = Person("Alice", 30)

# 打印对象的属性
print(p.name)  # 输出: Alice
print(p.age)   # 输出: 30

# 使用 delattr 删除属性
delattr(p, 'age')

# 尝试访问已删除的属性会抛出 AttributeError
try:
print(p.age)  # 抛出 AttributeError: 'Person' object has no attribute 'age'
except AttributeError as e:
print(e)

# 其他属性仍然可以访问
print(p.name)  # 输出: Alice

在这个例子中,我们定义了一个 Person 类,它有两个属性:nameage。然后我们创建了一个 Person 对象 p 并设置了这两个属性。接着我们使用 delattr 函数删除了 p 对象的 age 属性。当我们尝试访问已经删除的 age 属性时,Python 会抛出一个 AttributeError 异常。

当然,Python 的内置函数远不止上面列出的那些。这里列出一些其他的常用内置函数及其简短的描述和示例:

16. dir(object)

返回对象的属性列表。如果没有给定对象,则返回当前范围内的变量、方法和定义的类型列表。

print(dir())  # 输出当前作用域内的所有变量和函数
print(dir(str))  # 输出str类的所有方法和属性

17. divmod(a, b)

返回商和余数,作为一个包含两个元素的元组 (a // b, a % b)。

print(divmod(10, 3))  # 输出: (3, 1)

18. eval(expression[, globals[, locals]])

执行一个 Python 表达式,并返回表达式的值。

x = 1
print(eval('x + 1'))  # 输出: 2

19. exec(object[, globals[, locals]])

支持动态执行 Python 代码。

exec('x = 10')
print(x)  # 输出: 10

20. filter(function, iterable)

过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。

def is_even(n):
   return n % 2 == 0

print(filter(is_even, [1, 2, 3, 4, 5]))  # 输出: <filter object at ...>
print(list(filter(is_even, [1, 2, 3, 4, 5])))  # 输出: [2, 4]

21. float(x)

将 x 转换为一个浮点数。

print(float(10))  # 输出: 10.0

22. format(value[, format_spec])

格式化一个值。

print('{} {}'.format('Hello', 'World'))  # 输出: Hello World

23. frozenset(iterable)

返回一个冻结集合,即不能再添加或删除元素的集合。

f = frozenset([1, 2, 3])
print(f)  # 输出: frozenset({1, 2, 3})

24. globals()

返回当前全局符号表的字典。

print(globals())  # 输出全局变量的字典

25. hasattr(object, name)

检查对象是否包含给定的属性。

class MyClass:
    pass

obj = MyClass()
obj.x = 10
print(hasattr(obj, 'x'))  # 输出: True
print(hasattr(obj, 'y'))  # 输出: False

26. hash(object)

返回对象的哈希值(如果对象是不可哈希的,则抛出 TypeError)。

print(hash(10))  # 输出: 10 的哈希值

27. hex(x)

将整数 x 转换为小写的十六进制字符串。

print(hex(255))  # 输出: '0xff'

28. int(x[, base])

将 x 转换为一个整数。如果 x 不符合整数的要求,则抛出 ValueError。

print(int('123'))  # 输出: 123
print(int('1010', 2))  # 输出: 10(二进制转十进制)

29. isinstance(object, classinfo)

检查对象是否是指定类的实例,或是指定类的子类的实例。

print(isinstance(1, int))  # 输出: True

30. issubclass(class, classinfo)

检查一个类是否是另一个类的子类。

class A:
    pass

class B(A):
    pass

print(issubclass(B, A))  # 输出: True

31. iter(iterable)

获取迭代器对象。

iter是一个内置函数,用于获取一个迭代器对象。迭代器是一个可以记住遍历的位置的对象,它允许你一次访问集合(如列表、元组、字典、集合、字符串等)中的一个元素,而不需要暴露该集合的底层表示。

当你对一个对象调用iter函数时,它会返回一个迭代器。迭代器实现了__iter__()__next__()两个特殊方法。__iter__()方法返回迭代器对象本身,这样你就可以在迭代器上多次调用iter__next__()方法返回容器的下一个元素,当没有更多元素时,它会抛出一个StopIteration异常。

以下是一些使用iter的例子:

# 获取列表的迭代器
list_iter = iter([1, 2, 3, 4])
print(next(list_iter))  # 输出: 1
print(next(list_iter))  # 输出: 2

# 使用for循环遍历列表,实际上也是在使用迭代器
for item in [1, 2, 3, 4]:
print(item)  # 依次输出: 1 2 3 4

# 获取字典键的迭代器
dict_iter = iter({
   'a': 1, 'b': 2, 'c': 3})
print(next(dict_iter))  # 输出: 'a'

# 获取字符串的迭代器
str_iter = iter('hello')
print(next(str_iter))  # 输出: 'h'

# 创建自定义迭代器
class MyNumbers:
def __iter__(self):
    self.a = 1
    return self

def __next__(self):
    x = self.a
    self.a += 1
    return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))  # 输出: 1
print(next(myiter))  # 输出: 2

在上面的例子中,我们展示了如何获取列表、字典和字符串的迭代器,并如何使用next函数来逐个访问它们的元素。我们还创建了一个自定义的迭代器类MyNumbers,它实现了__iter____next__方法,允许我们创建一个迭代器对象并逐个访问其生成的数字。

iter函数也常用于与for循环一起使用,因为for循环在Python中实际上是使用迭代器来遍历集合的。当你对一个集合使用for循环时,Python会自动为你创建一个迭代器。

当然可以。Python的内置函数是Python解释器提供的,不需要导入任何模块就可以直接使用的函数。这些函数提供了基础的操作,如数学运算、类型转换、文件操作、内存管理等。

以下是一些其他常用的Python内置函数:

32. len(s)

返回对象(如字符串、列表、元组等)的长度或项目数。

print(len([1, 2, 3]))  # 输出: 3
print(len("hello"))    # 输出: 5

33. list(iterable)

将可迭代对象转换为列表。

print(list((1, 2, 3)))  # 输出: [1, 2, 3]
print(list('hello'))    # 输出: ['h', 'e', 'l', 'l', 'o']

34. locals()

返回当前局部符号表的字典。

def func():
   x = 10
   print(locals())  # 输出: {'x': 10}

func()

35. map(function, iterable, ...)

对可迭代对象的每个项目应用函数,并返回一个迭代器,该迭代器产生应用函数后的结果。

def square(x):
   return x ** 2

print(list(map(square, [1, 2, 3, 4])))  # 输出: [1, 4, 9, 16]

36. max(iterable, *[, key, default])

返回可迭代对象中的最大值。

print(max([1, 2, 3, 4]))  # 输出: 4
print(max(1, 2, 3, 4))    # 输出: 4

37. min(iterable, *[, key, default])

返回可迭代对象中的最小值。

print(min([1, 2, 3, 4]))  # 输出: 1
print(min(1, 2, 3, 4))    # 输出: 1

38. next(iterator[, default])

返回迭代器的下一个项目。如果提供了默认值,当迭代器耗尽时,将返回该值。

it = iter([1, 2, 3])
print(next(it))  # 输出: 1
print(next(it))  # 输出: 2
print(next(it, 'end'))  # 输出: 3
print(next(it, 'end'))  # 输出: 'end'

39. oct(x)

将整数 x 转换为八进制字符串。

print(oct(10))  # 输出: '0o12'

40. ord(c)

返回字符 c 的Unicode码点。

print(ord('A'))  # 输出: 65

41. pow(x, y[, z])

返回 x 的 y 次幂,如果提供了 z,则返回 x 的 y 次幂对 z 取模的结果。

print(pow(2, 3))      # 输出: 8
print(pow(2, 3, 5))   # 输出: 3

42. range(start, stop[, step])

返回一个表示范围的对象,通常用于循环。

for i in range(5):
    print(i)  # 输出: 0 1 2 3 4

43. reversed(seq)

返回序列的反向迭代器。

print(list(reversed([1, 2, 3, 4])))  # 输出: [4, 3, 2, 1]

44. round(number[, ndigits])

返回浮点数四舍五入后的值。

print(round(3.14159, 2))  # 输出: 3.14

45. set(iterable)

返回一个集合,该集合是输入迭代器的元素的无序集合。

set 是一种无序且不包含重复元素的数据集合类型。它提供了数学上集合的概念,即一组独特的对象,没有特定的顺序。set 类型用于存储多个元素,并且自动去除了重复的元素。

创建 set 类型的对象有几种方法:

  1. 使用大括号 {} 直接创建,并列出集合中的元素。
  2. 使用 set() 函数将其他可迭代对象(如列表、元组等)转换为集合。
  3. 使用 set() 函数和关键字参数,可以创建一个包含指定元素的集合。

以下是一些示例:

# 使用大括号创建集合
s1 = {
   1, 2, 3, 4}
print(s1)  # 输出: {1, 2, 3, 4}

# 使用set()函数创建集合
s2 = set([1, 2, 2, 3, 4, 4])  # 重复的元素会被自动去除
print(s2)  # 输出: {1, 2, 3, 4}

# 使用set()函数和关键字参数创建集合
s3 = set(range(5))  # 创建一个包含0到4的集合
print(s3)  # 输出: {0, 1, 2, 3, 4}

# 集合还支持集合运算,如并集、交集、差集等
s4 = {
   1, 2, 3, 5}
s5 = {
   4, 5, 6, 7}

# 并集
print(s4.union(s5))  # 输出: {1, 2, 3, 4, 5, 6, 7}

# 交集
print(s4.intersection(s5))  # 输出: {5}

# 差集(s4中存在但s5中不存在的元素)
print(s4.difference(s5))  # 输出: {1, 2, 3}

# 对称差集(存在于s4或s5中,但不同时存在于两者中的元素)
print(s4.symmetric_difference(s5))  # 输出: {1, 2, 3, 4, 6, 7}

# 判断一个元素是否在集合中
print(3 in s4)  # 输出: True
print(8 in s4)  # 输出: False

# 集合不支持索引和切片操作,因为它们是无序的
# s4[0]  # 这将引发TypeError

set 类型提供了许多有用的方法,如 add()remove()discard()pop()clear() 等,用于管理集合中的元素。由于 set 是无序的,因此它们不支持索引和切片操作。

set 类型也支持集合运算,如并集、交集、差集和对称差集,这些都可以通过相应的方法来实现。这些运算在集合论和数据处理中非常有用。

二、相关链接

  1. Python下载安装中心
  2. Python官网
  3. Python软件下载
  4. 「Python系列」Python简介及案例
  5. 「Python系列」Python基础语法/数据类型
  6. 「Python系列」Python解释器
  7. 「Python系列」Python运算符
  8. 「Python系列」Python数据结构
  9. 「Python系列」Python元组
  10. 「Python系列」Python集合
  11. 「Python系列」Python列表
相关文章
|
1天前
|
Python
Python闭包函数和计时器
本文介绍了闭包函数的概念,它允许内部函数引用外部作用域的变量但无法修改它们。示例展示了如何使用闭包来封装函数。接着,文章讨论了如何在函数调用时添加开始和结束的打印语句,通过传递函数作为参数实现。然后,文章引入装饰器,通过闭包定义了一个`timer`装饰器,用于在函数执行前后打印消息。最后,给出了一个练习,实现了一个计算函数执行时间的装饰器,处理了带有参数的被装饰函数。
12 1
|
17小时前
|
Python
Python使用isinstance()函数
【5月更文挑战第10天】Python使用isinstance()函数
9 2
|
16小时前
|
缓存 Python
Python中的装饰器:优雅而强大的函数装饰技术
在Python编程中,装饰器是一种强大而灵活的技术,它可以使函数具有额外的功能,而不需要改变函数的核心代码。本文将深入探讨装饰器的原理、用法以及实际应用场景,帮助读者更好地理解和利用这一重要的Python编程工具。
|
1天前
|
Python
PyQt---------信号与槽函数的关系
PyQt---------信号与槽函数的关系
11 1
|
1天前
|
测试技术 开发者 Python
Python检查函数和方法的输入/输出
【5月更文挑战第5天】Python检查函数和方法的输入/输出
13 1
|
1天前
|
Python
在Python中,利用`os模块`的`path.exists()`函数可判断文件是否存
【5月更文挑战第12天】在Python中,利用`os模块`的`path.exists()`函数可判断文件是否存在,该函数对路径进行检查,存在则返回True,不存在则返回False。示例代码展示了如何检查'example.txt'文件是否存在并相应打印消息。此外,`os.path.isfile()`用于确认路径是否为文件,仅当是文件时返回True,否则返回False,同样配以示例说明其用法。
23 2
|
1天前
|
Python
【Python操作基础】——函数
【Python操作基础】——函数
|
1天前
|
Python
Python的全局变量作用于整个程序,生命周期与程序相同,而局部变量仅限函数内部使用,随函数执行结束而销毁。
【5月更文挑战第11天】Python的全局变量作用于整个程序,生命周期与程序相同,而局部变量仅限函数内部使用,随函数执行结束而销毁。在函数内部修改全局变量需用`global`关键字声明,否则会创建新局部变量。
104 2
|
1天前
|
Java C# 开发者
Python 中的类型注解是一种用于描述变量、函数参数和返回值预期类型的机制
【5月更文挑战第8天】Python的类型注解提升代码可读性和可维护性,虽非强制,但利于静态类型检查(如Mypy)。包括:变量注解、函数参数和返回值注解,使用内置或`typing`模块的复杂类型,自定义类型注解,以及泛型模拟。类型注解可在变量声明、函数定义和注释中使用,帮助避免类型错误,提高开发效率。
23 6
|
1天前
|
存储 Python
【Python 基础】解释reduce函数的工作原理
【5月更文挑战第6天】【Python 基础】解释reduce函数的工作原理