Python 66 个内置函数!附代码

Python有许多内置函数,共有66个。以下是这些内置函数的详细解释和示例代码

1.abs(x): 返回一个数的绝对值。

x = -10 
print(abs(x))  # 输出:10 

2.all(iterable): 如果可迭代对象中所有元素都为真,则返回True;否则返回False。

iterable = [True, True, False] 
print(all(iterable))  # 输出:False 

3.any(iterable): 如果可迭代对象中任何一个元素为真,则返回True;否则返回False。

iterable = [False, False, True] 
print(any(iterable))  # 输出:True 

4.bin(x): 将一个整数转换为二进制字符串。

x = 10 
print(bin(x))  # 输出:0b1010 

5.bool(x): 将一个值转换为布尔类型。

x = 0 
print(bool(x))  # 输出:False 

6.bytearray([source[, encoding[, errors]]]): 创建一个可变的字节数组对象。

source = b'Hello' 
arr = bytearray(source) 
print(arr)  # 输出:bytearray(b'Hello') 

7.bytes([source[, encoding[, errors]]]): 创建一个不可变的字节对象。

source = 'Hello' 
b = bytes(source, encoding='utf-8') 
print(b)  # 输出:b'Hello' 

8.callable(object): 检查一个对象是否可调用(函数、方法等)。

def func():
    pass 
print(callable(func))  # 输出:True 

9.chr(i): 返回一个Unicode编码的整数对应的字符。

i = 65 
print(chr(i))  # 输出:A 

10.classmethod(func): 将一个普通方法转换为类方法。

class MyClass:
    attr = 10
    
    @classmethod
    def class_method(cls):
        print(cls.attr)

MyClass.class_method()  # 输出:10 

11.compile(source, filename, mode[, flags[, dont_inherit]]): 编译源代码为代码或AST对象。

source = "print('Hello, World!')" 
code = compile(source, filename="", mode="exec") 
exec(code)  # 输出:Hello, World! 

12.complex(real[, imag]): 创建一个复数。

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

13.delattr(object, name): 删除对象的属性。

class MyClass:
    attr = 10

obj = MyClass()
delattr(obj, 'attr') 
print(hasattr(obj, 'attr'))  # 输出:False 

14.dict([arg]): 创建一个字典。

d = dict(a=1, b=2, c=3) 
print(d)  # 输出:{'a': 1, 'b': 2, 'c': 3} 

15.dir([object]): 返回一个包含对象所有属性和方法名的列表。

class MyClass:
    attr = 10
    def method(self):
        pass

obj = MyClass() 
print(dir(obj))

16.divmod(a, b): 返回a除以b的商和余数。

a = 10
b = 3
result = divmod(a, b) 
print(result)  # 输出:(3, 1) 

17.enumerate(iterable, start=0): 返回一个枚举对象,包含索引和值。

iterable = ['a', 'b', 'c'] 
for i, value in enumerate(iterable): 
    print(i, value) # 输出: # 0 a # 1 b # 2 c 

18.eval(expression[, globals[, locals]]): 执行一个字符串表达式,并返回结果。

expression = "2 + 3" 
result = eval(expression) 
print(result)  # 输出:5 

19.exec(object[, globals[, locals]]): 执行Python代码。

code ="""
x = 5
if x > 0:
    print("Positive")
else:
    print("Non-positive")
""" exec(code)  # 输出:Positive 

20.filter(function, iterable): 使用给定的函数对可迭代对象进行过滤。

def is_positive(x): 
    return x > 0 
numbers = [1, -2, 3, -4, 5] 
result = filter(is_positive, numbers) 
print(list(result))  # 输出:[1, 3, 5] 

21.float(x): 将一个数转换为浮点数。

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

22.format(value[, format_spec]): 格式化一个值。

value = 3.14159
result = format(value, ".2f") 
print(result)  # 输出:3.14 

23.frozenset([iterable]): 创建一个不可变的集合。

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

24.getattr(object, name[, default]): 返回对象的属性值。

class MyClass:
    attr = 10

obj = MyClass() 
print(getattr(obj, 'attr'))  # 输出:10 

25.globals(): 返回当前全局作用域的字典。

print(globals())

26.hasattr(object, name): 检查对象是否有指定的属性。

class MyClass:
    attr = 10

obj = MyClass() 
print(hasattr(obj, 'attr'))  # 输出:True 

27.hash(object): 返回对象的哈希值。

x = 10 
print(hash(x))

28.help([object]): 获取对象的帮助信息。

help(list)

29.hex(x): 将一个整数转换为十六进制字符串。

x = 255 
print(hex(x))  # 输出:0xff 

30.id(object): 返回对象的唯一标识符。

x = 10 
print(id(x))

31.input([prompt]): 接收用户输入,并返回一个字符串。

name = input("请输入您的姓名:") 
print("您好," + name + "!") 

32.int(x=0): 将一个数转换为整数。

x = 3.14 
print(int(x))  # 输出:3 

33.isinstance(object, classinfo): 检查一个对象是否为指定类或类型元组的实例。

class MyClass:
    pass

obj = MyClass() 
print(isinstance(obj, MyClass))  # 输出:True 

34.issubclass(class, classinfo): 检查一个类是否为另一个类的子类。

class Parent:
    pass

class Child(Parent):
    pass 
print(issubclass(Child, Parent))  # 输出:True' 

35.iter(iterable[, sentinel]): 创建一个迭代器对象。

iterable = [1, 2, 3]
iterator = iter(iterable) 
print(next(iterator))  # 输出:1 

36.len(s): 返回一个对象的长度(元素个数)。

s = "Hello" 
print(len(s))  # 输出:5 

37.list([iterable]): 创建一个列表。

iterable = (1, 2, 3)
lst = list(iterable) 
print(lst)  # 输出:[1, 2, 3] 

38.locals(): 返回当前局部作用域的字典。

print(locals())

39.map(function, iterable, ...): 对可迭代对象中的每个元素应用一个函数。

def square(x): 
    return x ** 2 
numbers = [1, 2, 3, 4, 5] 
result = map(square, numbers) 
print(list(result))  # 输出:[1, 4, 9,16, 25] 

40.max(iterable[, key]): 返回可迭代对象中的最大值。

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

41.memoryview(obj): 创建一个内存视图对象,用于访问其他对象的内存。

lst = [1, 2, 3, 4, 5]
mv = memoryview(lst) 
print(mv[0])  # 输出:1 

42.min(iterable[, key]): 返回可迭代对象中的最小值。

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

43.next(iterator[, default]): 返回迭代器中的下一个元素。

iterable = [1, 2, 3]
iterator = iter(iterable) 
print(next(iterator))  # 输出:1 

44.object(): 返回一个新的空对象。

obj = object() 
print(obj)

45.oct(x): 将一个整数转换为八进制字符串。

x = 8 
print(oct(x))  # 输出:0o10 

46.open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None): 打开一个文件,并返回文件对象。

file = open("example.txt", "w")
file.write("Hello, World!")
file.close()

47.ord(c): 返回一个字符的Unicode编码。

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

48.pow(x, y[, z]): 返回x的y次幂,如果提供z,则返回x的y次幂对z取模的结果。

x = 2
y = 3
z = 5
result = pow(x, y, z) 
print(result)  # 输出:3 

49.print(objects, sep=' ', end='\n', file=sys.stdout, flush=False): 打印输出到控制台。

name = "Alice" 
age = 25 
print("My name is", name, "and I am", age, "years old.") # 输出:My name is Alice and I am 25 years old. 

50.property(fget=None, fset=None, fdel=None, doc=None): 创建一个属性。

class MyClass:
    def __init__(self):
        self._attr = 0
    
    @property
    def attr(self):
        return self._attr
    
    @attr.setter
    def attr(self, value):
        self._attr = value

obj = MyClass()
obj.attr = 10 
print(obj.attr)  # 输出:10 

51.range(stop): 返回一个包含从0到stop-1的整数序列的可迭代对象。

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

52.repr(object): 返回一个对象的字符串表示形式。

s = "Hello" 
print(repr(s))  # 输出:'Hello' 

**53.reversed(seq): **返回一个反向的迭代器对象。

seq = [1, 2, 3]
rev_seq = reversed(seq) 
print(list(rev_seq))  # 输出:[3, 2, 1] 

54.round(number[, ndigits]): 对一个数进行四舍五入。

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

55.set([iterable]): 创建一个集合。

iterable = [1, 2, 3]
s = set(iterable) 
print(s)  # 输出:{1, 2, 3} 

56.setattr(object, name, value): 设置对象的属性值。

class MyClass:
    attr = 10

obj = MyClass()
setattr(obj, 'attr', 20) 
print(obj.attr)  # 输出:20 

57.slice(stop): 创建一个切片对象,用于切片操作。

numbers = [1, 2, 3, 4, 5]
s = slice(2) 
print(numbers[s])  # 输出:[1, 2] 

58.sorted(iterable[, key][, reverse]): 返回一个排序后的列表。

numbers = [3, 1, 4, 2, 5]
sorted_numbers = sorted(numbers) 
print(sorted_numbers)  # 输出:[1, 2, 3, 4, 5] 

59.staticmethod(function): 将一个函数转换为静态方法。

class MyClass:
    @staticmethod
    def my_method():
        
print("This is a static method.")

MyClass.my_method()  # 输出:This is a static method. 

60.str(object=''): 将一个对象转换为字符串。

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

61.sum(iterable[, start]): 返回可迭代对象中所有元素的总和。

numbers = [1, 2, 3, 4, 5] 
print(sum(numbers))  # 输出:15 

62.super([type[, object-or-type]]): 返回父类的对象。

class Parent:
    def __init__(self):
        self.attr = 10

class Child(Parent):
    def __init__(self):
        super().__init__()

child = Child() 
print(child.attr)  # 输出:10 

63.tuple([iterable]): 创建一个元组。

iterable = [1, 2, 3]
t = tuple(iterable) 
print(t)  # 输出:(1, 2, 3) 

64.type(object): 返回一个对象的类型。

x = 10 
print(type(x))  # 输出:<class 'int'> 

65.vars([object]): 返回对象的属性和属性值的字典。

class MyClass:
    attr = 10

obj = MyClass() 
print(vars(obj))  # 输出:{'attr': 10} 

*66.zip(iterables): 将多个可迭代对象中对应位置的元素打包成元组,并返回一个由这些元组组成的可迭代对象。

numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
zipped = zip(numbers, letters) 
print(list(zipped))  # 输出:[(1, 'a'), (2, 'b'), (3, 'c')] 

以上是Python中一些常用的内建函数的介绍和示例。希望能对你有所帮助!

- 本文来自网络,如有侵权,请联系本站处理。

2024-03   阅读(31)   评论(0)
 标签: program Python

涨知识
麦克纳姆轮

麦克纳姆轮的移动方式是基于一个有许多位于机轮周边的轮轴的中心轮的原理上,这些成角度的周边轮轴把一部分的机轮转向力转化到一个机轮法向力上面。

评论:
相关文章
一文详尽 Python 函数式编程技术

本文对 Python 中的函数式编程技术进行了简单的入门介绍。


用Python优雅地编写LaTeX

latexify是用于生成 LaTeX 数学公式的 Python 库。LaTeX 是一种基于 ΤΕΧ 的排版系统,对于展示复杂的数学公式表现极为出色。


使用Python开发Android应用的简易教程

在过去,如果你想要开发Android应用,你需要掌握Java或者Kotlin等编程语言,但是现在,Python也可以用来开发Android应用了。


Thonny 4.1.3 下载

Thonny是一款免费的、开源的、易于使用的编程语言,旨在为初学者提供简单易用的编程环境。 Thonny的语法简洁易懂,同时还支持自动补全和语法高亮,使得编程变得更加便捷。


使用Python创建3D模型(3D打印+乐高)

在设计一些机壳、玩具等3D项目时,往往需要精确的尺寸控制。徒手绘制对手残党不友好,使用CAD软件的自带命令又会增加学习成本,还不如使用万金油Python搞定。

搜索
最新课件
小鹏STEM教研服务

专属教研服务系统,助您构建STEM课程体系,打造一站式教学环境。