在本章中,我们将详细介绍 Python3 中的一些内置函数。这些函数无需导入任何模块即可使用,并且在日常编程中非常实用。
abs()
abs() 函数返回一个数的绝对值。对于整数和浮点数都适用。
print(abs(-5)) # 输出:5 print(abs(3.14)) # 输出:3.14
all()
all() 函数用于判断给定的可迭代对象中的所有元素是否都为真值(或可迭代对象为空)。如果所有元素都为真,则返回 True;否则返回 False。
print(all([True, True, True])) # 输出:True print(all([True, False, True])) # 输出:False
any()
any() 函数用于判断给定的可迭代对象中的任意元素是否为真值。只要有一个元素为真,则返回 True;如果所有元素都为假或可迭代对象为空,则返回 False。
print(any([False, False, False])) # 输出:False print(any([False, True, False])) # 输出:True
ascii()
ascii() 函数用于获取对象的可打印表示形式,返回字符串。它会将非ASCII字符替换为相应的转义序列。
print(ascii('你好')) # 输出:'\\u4f60\\u597d'bin()
bin() 函数用于将整数转换为二进制字符串,前缀为 '0b'。
print(bin(10)) # 输出:'0b1010'
bool()
bool() 函数用于将给定值转换为布尔值。如果没有参数,返回 False。
print(bool(0)) # 输出:False
print(bool(1)) # 输出:True
print(bool("")) # 输出:False
print(bool("hello")) # 输出:Truebytearray()
bytearray() 函数用于创建一个可变的字节序列对象。
data = bytearray(4) data[0] = 65 data[1] = 66 data[2] = 67 data[3] = 68 print(data) # 输出:bytearray(b'ABCD')
bytes()
bytes() 函数用于创建一个不可变的字节序列对象。
data = bytes([65, 66, 67, 68]) print(data) # 输出:b'ABCD'
callable()
callable() 函数用于检查一个对象是否可调用。如果可调用,则返回 True;否则返回 False。
// www.javascriptcn.com code example
def func():
pass
class MyClass:
def method(self):
pass
print(callable(func)) # 输出:True
print(callable(MyClass())) # 输出:False
print(callable(MyClass.method)) # 输出:Truechr()
chr() 函数用于返回 Unicode 编码对应的字符。
print(chr(65)) # 输出:A print(chr(97)) # 输出:a
classmethod()
classmethod() 函数用于将方法标记为类方法。通过使用 @classmethod 装饰器,可以将一个方法转换为类方法。
class MyClass:
@classmethod
def my_class_method(cls):
return "Hello from class method"
print(MyClass.my_class_method()) # 输出:Hello from class methodcompile()
compile() 函数用于将字符串编译成代码或 AST 对象。该函数常用于动态执行 Python 代码。
code_str = 'x=5\ny=10\nprint("sum =", x+y)'
code_obj = compile(code_str, 'sum_string', 'exec')
exec(code_obj)complex()
complex() 函数用于创建复数或转换为复数。
print(complex(1, 2)) # 输出:(1+2j)
print(complex('1+2j')) # 输出:(1+2j)delattr()
delattr() 函数用于删除对象的指定属性。
class MyClass:
def __init__(self):
self.x = 10
obj = MyClass()
print(obj.x) # 输出:10
delattr(obj, 'x')
print(hasattr(obj, 'x')) # 输出:Falsedict()
dict() 函数用于创建字典。
my_dict = dict(name="Alice", age=25)
print(my_dict) # 输出:{'name': 'Alice', 'age': 25}dir()
dir() 函数用于返回对象的属性和方法列表。
print(dir(list)) # 输出:['__add__', '__class__', '__contains__', ...]
divmod()
divmod() 函数用于同时计算除法和取余操作的结果。
print(divmod(10, 3)) # 输出:(3, 1)
enumerate()
enumerate() 函数用于将一个可迭代对象组合为一个索引序列,同时列出数据和数据下标。
for i, value in enumerate(['apple', 'banana', 'orange']):
print(i, value)
# 输出:
# 0 apple
# 1 banana
# 2 orangeeval()
eval() 函数用于执行一个字符串表达式,并返回表达式的值。
x = 1
print(eval('x + 1')) # 输出:2exec()
exec() 函数用于动态执行 Python 代码。
code_str = """ x = 5 y = 10 print(x + y) """ exec(code_str) # 输出:15
filter()
filter() 函数用于过滤序列,过滤掉不符合条件的元素。
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers)) # 输出:[2, 4, 6]float()
float() 函数用于将一个数值或字符串转换为浮点数。
print(float(5)) # 输出:5.0
print(float('5.5')) # 输出:5.5format()
format() 函数用于格式化字符串。
print(format(123.456, '.2f')) # 输出:123.46
frozenset()
frozenset() 函数用于创建一个不可变的集合。
my_set = frozenset([1, 2, 3, 4, 5])
print(my_set) # 输出:frozenset({1, 2, 3, 4, 5})getattr()
getattr() 函数用于返回对象的指定属性值。如果属性不存在,则返回默认值。
class MyClass:
def __init__(self):
self.x = 10
obj = MyClass()
print(getattr(obj, 'x')) # 输出:10
print(getattr(obj, 'y', 'default_value')) # 输出:default_valueglobals()
globals() 函数用于返回全局符号表的字典。
print(globals()) # 输出:全局变量字典
hasattr()
hasattr() 函数用于检查对象是否有指定属性。
class MyClass:
def __init__(self):
self.x = 10
obj = MyClass()
print(hasattr(obj, 'x')) # 输出:True
print(hasattr(obj, 'y')) # 输出:Falsehash()
hash() 函数用于返回对象的哈希值。
print(hash('hello')) # 输出:哈希值help()
help() 函数用于获取对象的帮助信息。
help(print) # 输出:print() 的帮助信息
hex()
hex() 函数用于将整数转换为十六进制字符串,前缀为 '0x'。
print(hex(255)) # 输出:'0xff'
id()
id() 函数用于返回对象的唯一标识符。
x = 10 print(id(x)) # 输出:对象的唯一标识符
input()
input() 函数用于从标准输入读取一行文本,默认提示符为 '> '。
name = input('请输入你的名字:')
print('你好,' + name)int()
int() 函数用于将一个数值或字符串转换为整数。
print(int(5.5)) # 输出:5
print(int('5')) # 输出:5isinstance()
isinstance() 函数用于判断对象是否是某个类型。
print(isinstance(5, int)) # 输出:True
print(isinstance('hello', str)) # 输出:Trueissubclass()
issubclass() 函数用于判断一个类是否是另一个类的子类。
class Base:
pass
class Derived(Base):
pass
print(issubclass(Derived, Base)) # 输出:Trueiter()
iter() 函数用于创建迭代器对象。
numbers = [1, 2, 3, 4, 5] it = iter(numbers) print(next(it)) # 输出:1 print(next(it)) # 输出:2
len()
len() 函数用于返回对象的长度。
print(len([1, 2, 3, 4])) # 输出:4
print(len('hello')) # 输出:5list()
list() 函数用于创建列表。
print(list('hello')) # 输出:['h', 'e', 'l', 'l', 'o']locals()
locals() 函数用于返回当前局部符号表的字典。
print(locals()) # 输出:局部变量字典
map()
map() 函数用于将指定函数应用于指定序列的每个元素,并返回一个迭代器。
def square(x):
return x * x
numbers = [1, 2, 3, 4, 5]
squares = map(square, numbers)
print(list(squares)) # 输出:[1, 4, 9, 16, 25]max()
max() 函数用于返回可迭代对象中的最大值。
print(max([1, 2, 3, 4, 5])) # 输出:5
memoryview()
memoryview() 函数用于创建内存视图对象。
data = bytearray([1, 2, 3, 4, 5]) mv = memoryview(data) print(mv[0]) # 输出:1
min()
min() 函数用于返回可迭代对象中的最小值。
print(min([1, 2, 3, 4, 5])) # 输出:1
next()
next() 函数用于从迭代器中获取下一个项目。
numbers = [1, 2, 3, 4, 5] it = iter(numbers) print(next(it)) # 输出:1 print(next(it)) # 输出:2
object()
object() 函数用于创建一个新的对象。
obj = object() print(type(obj)) # 输出:<class 'object'>
oct()
oct() 函数用于将整数转换为八进制字符串,前缀为 '0o'。
print(oct(8)) # 输出:'0o10'
open()
open() 函数用于打开文件并返回一个文件对象。
with open('example.txt', 'w') as file:
file.write('Hello, world!')ord()
ord() 函数用于返回一个字符的 Unicode 编码。
print(ord('A')) # 输出:65pow()
pow() 函数用于计算幂。
print(pow(2, 3)) # 输出:8
print()
print() 函数用于打印输出到标准输出设备。
print('Hello, world!')property()
property() 函数用于返回一个属性值。
// www.javascriptcn.com code example
class MyClass:
def __init__(self):
self._x = 0
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
obj = MyClass()
print(obj.x) # 输出:0
obj.x = 10
print(obj.x) # 输出:10range()
range() 函数用于生成一个整数序列。
for i in range(5):
print(i)
# 输出:
# 0
# 1
# 2
# 3
# 4repr()
repr() 函数用于获取对象的可打印表示形式。
print(repr('hello')) # 输出:"'hello'"reversed()
reversed() 函数用于返回反向迭代器。
// www.javascriptcn.com code example
numbers = [1, 2, 3, 4, 5]
for num in reversed(numbers):
print(num)
# 输出:
# 5
# 4
# 3
# 2
# 1round()
round() 函数用于四舍五入。
print(round(3.7)) # 输出:4
set()
set() 函数用于创建集合。
print(set([1, 2, 3, 4, 5])) # 输出:{1, 2, 3, 4, 5}setattr()
setattr() 函数用于设置对象的指定属性值。
class MyClass:
def __init__(self):
self.x = 0
obj = MyClass()
setattr(obj, 'x', 10)
print(obj.x) # 输出:10slice()
slice() 函数用于创建切片对象。
numbers = [1, 2, 3, 4, 5] sliced = numbers[slice(1, 4)] print(sliced) # 输出:[2, 3, 4]
sorted()
sorted() 函数用于对可迭代对象进行排序。
numbers = [3, 1, 4, 1, 5, 9, 2] sorted_numbers = sorted(numbers) print(sorted_numbers) # 输出:[1, 1, 2, 3, 4, 5, 9]
staticmethod()
staticmethod() 函数用于将方法标记为静态方法。
class MyClass:
@staticmethod
def my_static_method():
return "Hello from static method"
print(MyClass.my_static_method()) # 输出:Hello from static methodstr()
str() 函数用于将一个数值或对象转换为字符串。
print(str(5)) # 输出:'5'
sum()
sum() 函数用于求和。
numbers = [1, 2, 3, 4, 5] print(sum(numbers)) # 输出:15
super()
super() 函数用于返回父类的对象。
// www.javascriptcn.com code example
class Base:
def method(self):
print('Base method')
class Derived(Base):
def method(self):
super().method()
print('Derived method')
obj = Derived()
obj.method()
# 输出:
# Base method
# Derived methodtuple()
tuple() 函数用于创建元组。
print(tuple([1, 2, 3, 4, 5])) # 输出:(1, 2, 3, 4, 5)
type()
type() 函数用于返回对象的类型。
print(type(5)) # 输出:<class 'int'>
vars()
vars() 函数用于返回对象的 __dict__ 属性。
class MyClass:
def __init__(self):
self.x = 10
obj = MyClass()
print(vars(obj)) # 输出:{'x': 10}zip()
zip() 函数用于将多个可迭代对象打包成元组。
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
zipped = zip(names, ages)
print(list(zipped)) # 输出:[('Alice', 25), ('Bob', 30), ('Charlie', 35)]以上是 Python3 内置函数的部分介绍,这些函数覆盖了常见的数据处理、类型转换、对象操作等方面。通过熟练掌握这些内置函数,可以大大提高编程效率和代码质量。