Python函数列表:常用函数大全
Python 是一种面向对象的高级编程语言,由于其语法简单,易学易用,已成为 的编程语言之一。Python 的内置函数可以节省编程的时间和精力,而且它们是 Python 程序中的常用功能,因此熟练使用这些函数非常重要。下面是常用函数大全,总结了 Python 的内置函数,以及它们的用法和示例。
1. abs(x):返回 x 的绝对值
x = -3 print(abs(x)) # 3
2. all(iterable):如果 iterable 中所有的元素都为 true,则返回 true
iter_list = [1, 0, 2, 3] print(all(iter_list)) # False
3. any(iterable):如果 iterable 中任何一个元素为 true,则返回 true
iter_list = [0, False, 2, 3] print(any(iter_list)) # True
4. ascii(obj):返回一个可打印的字符串,其中包含 obj 的表示形式
print(ascii('中国')) # '\u4e2d\u56fd'
5. bin(x):将整数转换为二进制字符串
x = 123 print(bin(x)) # '0b1111011'
6. bool(x):将 x 转换为布尔类型
x = 'False' print(bool(x)) # True
7. bytearray(iterable):返回一个可修改的 bytes 对象
lst = [10, 20, 30] byte_arr = bytearray(lst) print(byte_arr) # bytearray(b' \x14\x1e')
8. bytes(iterable):返回一个不可修改的 bytes 对象
lst = [10, 20, 30] byte_obj = bytes(lst) print(byte_obj) # b' \x14\x1e'
9. callable(obj):如果 obj 是可调用的,则返回 true;否则返回 false
def add_nums(a, b):
return a + b
print(callable(add_nums)) # True
10. chr(i):返回对应于 Unicode 码点 i 的字符
print(chr(9731)) # '?'
11. classmethod():返回一个类方法
class Rectangle:
width = 0
height = 0
def __init__(self, w, h):
self.width = w
self.height = h
@classmethod
def square(cls, side):
return cls(side, side)
square = Rectangle.square(5)
print(square.width) # 5
print(square.height) # 5
12. compile(source, filename, mode, flags=0, dont_inherit=False):将 source 解释为字节代码对象
code = "print('Hello World')"
compiled_code = compile(code, filename='', mode='exec')
exec(compiled_code) # Hello World
13. complex(real, imaginary):返回一个复数对象
cplx = complex(2, 3) print(cplx) # (2+3j)
14. delattr(obj, name):删除对象指定的属性
class MyClass:
age = 20
name = 'John'
obj = MyClass()
print(obj.age) # 20
delattr(MyClass, 'age')
print(obj.age) # AttributeError: 'MyClass' object has no attribute 'age'
15. dict():返回一个新的空字典对象
dict_obj = dict()
dict_obj['name'] = 'John'
dict_obj['age'] = 30
print(dict_obj) # {'name': 'John', 'age': 30}
16. dir(obj):列出对象所有的属性和方法
class MyClass:
def func1():
pass
def func2():
pass
obj = MyClass()
print(dir(obj))
17. divmod(x, y):返回一个包含商和余数的元组
print(divmod(10, 3)) # (3, 1)
18. enumerate(iterable, start=0):返回一个包含索引和元素的元组序列
lst = ['apple', 'banana', 'orange']
for idx, item in enumerate(lst):
print(idx, item)
19. eval(expression, globals=None, locals=None):将字符串转换为可执行的代码
x = 1
y = 2
eval('x + y') # 3
20. exec(object, globals=None, locals=None):将字符串作为代码执行
code = "print('Hello World')"
exec(code) # Hello World
21. filter(function, iterable):返回一个符合条件的迭代器
lst = [1, 2, 3, 4, 5] new_lst = filter(lambda x: x > 3, lst) print(list(new_lst)) # [4, 5]
22. float(x):将一个字符串或数字转换为浮点数
x = '10.5' print(float(x)) # 10.5
23. format(value, format_spec):返回 value 的格式化版本
x = 10
print("{:.2f}".format(x)) # 10.00
24. frozenset(iterable):返回一个不可变的集合
frz_set = frozenset([1, 2, 3, 4, 5])
print(frz_set) # frozenset({1, 2, 3, 4, 5})
25. getattr(obj, name):返回对象的指定属性值
class MyClass:
age = 20
name = 'John'
obj = MyClass()
print(getattr(obj, 'age')) # 20
26. globals():返回全局命名空间的字典
print(globals())
27. hasattr(obj, name):如果对象有指定属性,则返回 True,否则返回 False
class MyClass:
age = 20
name = 'John'
obj = MyClass()
print(hasattr(obj, 'name')) # True
28. hash(obj):返回对象的哈希值
print(hash('Hello World')) # -7034076133637425540
29. help(obj):返回对象的帮助信息
lst = [] help(lst)
30. hex(x):返回一个整数的十六进制表示
x = 255 print(hex(x)) # 0xff
31. id(obj):返回对象的 标识符
x = 10 y = x print(id(x)) # 140722579434672 print(id(y)) # 140722579434672
32. input(prompt=None):从用户获取输入的值
name = input('What is your name? ')
print('Your name is {}'.format(name))
33. int(x):将一个字符串或浮点数转换为整数
x = '10' print(int(x)) # 10
34. isinstance(obj, class):如果 obj 是 class 的实例,则返回 True,否则返回 False
class Rectangle:
pass
square = Rectangle()
print(isinstance(square, Rectangle)) # True
35. issubclass(subclass, class):如果 subclass 是 class 的子类,则返回 True,否则返回 False
class Rectangle:
pass
class Square(Rectangle):
pass
print(issubclass(Square, Rectangle)) # True
36. iter(obj, sentinel):返回一个迭代器
lst = [1, 2, 3, 4, 5] itr = iter(lst) print(next(itr)) # 1
37. len(obj):返回对象的长度或元素个数
lst = [1, 2, 3, 4, 5] print(len(lst)) # 5
38. list(iterable):将一个可迭代对象转换为列表
tpl = (1, 2, 3, 4, 5) print(list(tpl)) # [1, 2, 3, 4, 5]
39. locals():返回局部命名空间的字典
`
def func():
x = 1
