Python内置内容大揭秘:变量、函数与探索技巧 欢迎来到Python内置内容的奇妙世界!这里就像Python的“百宝箱”,装满了各种开箱即用的工具,让你编程时少走弯路,多写优雅代码。今天,我们就来一场深度探秘之旅!
一、如何查看Python内置内容? 在探索具体内容之前,先学会如何发现宝藏!Python提供了几种查看内置内容的方法:
1. dir(__builtins__) - 你的内置内容地图 print ("Python内置内容列表:" )for item in dir (__builtins__): print (item, end=", " ) import pprintpprint.pprint(dir (__builtins__), compact=True )
2. 使用help()函数 - 内置帮助手册 help (print ) help ('builtins' )
3. 区分类型查看 builtin_funcs = [name for name in dir (__builtins__) if not name.startswith('__' ) and not name[0 ].islower()] builtin_exceptions = [name for name in dir (__builtins__) if name[0 ].isupper() and name not in ['True' , 'False' , 'None' ]] print ("内置函数:" , builtin_funcs)print ("内置异常:" , builtin_exceptions)
二、内置变量(常量)详解 这些是Python中的“固定标志”,像交通信号灯一样告诉程序该往哪走。
1. True 和 False - 布尔双雄 is_python_fun = True is_java_better = False print (f"Python有趣吗?{is_python_fun} " )print (f"1 > 2 吗?{1 > 2 } " ) if True : print ("这个总是会执行!" ) true_copy = True
2. None - 空无一物的艺术家 result = None print (f"结果是:{result} " ) print (f"result的类型是:{type (result)} " ) def find_user (user_id ): if user_id > 100 : return {"name" : "小明" , "age" : 20 } return None user = find_user(50 ) if user is None : print ("用户不存在!" ) if not None : print ("None就是False!" )
3. Ellipsis / ... - 省略号先生 print (Ellipsis ) print (...) import numpy as nparr = np.array([[[1 , 2 ], [3 , 4 ]], [[5 , 6 ], [7 , 8 ]]]) print (arr[..., 0 ]) def function_to_be_implemented_later (): ... class IncompleteClass : """待完善的类""" ... from typing import Tuple def get_data () -> Tuple [int , ...]: return (1 , 2 , 3 , 4 , 5 )
4. NotImplemented - “我做不到”的优雅表达 class Vector : def __init__ (self, x, y ): self .x = x self .y = y def __add__ (self, other ): if isinstance (other, Vector): return Vector(self .x + other.x, self .y + other.y) return NotImplemented v1 = Vector(1 , 2 ) v2 = Vector(3 , 4 ) try : result = v1 + "字符串" except TypeError as e: print (f"错误信息:{e} " ) v3 = v1 + v2 print (f"向量相加:({v3.x} , {v3.y} )" )
5. __debug__ - 调试小助手 print (f"调试模式:{__debug__ } " )if __debug__ : print ("这是在调试模式下才会打印的信息" ) else : pass assert 1 == 1 , "数学崩溃了!"
三、内置函数精选详解 Python有70多个内置函数,这里精选最常用、最重要的进行详细介绍。
1. 类型相关函数 type() - 身份调查员print (type (42 )) print (type (3.14 )) print (type ("Hello" )) print (type ([1 , 2 , 3 ])) print (type ({"a" : 1 })) MyClass = type ('MyClass' , (), {'x' : 10 }) obj = MyClass() print (f"动态创建的类实例属性:{obj.x} " )
isinstance() 和 issubclass() - 家族关系鉴定师num = 123 print (isinstance (num, int )) print (isinstance (num, (int , float , str ))) class Animal : pass class Dog (Animal ): pass class Cat (Animal ): pass print (issubclass (Dog, Animal)) print (issubclass (Dog, Cat)) def process_data (data ): if isinstance (data, list ): return sum (data) elif isinstance (data, dict ): return list (data.values()) else : return str (data)
callable() - “可调用吗?”测试器def say_hello (): print ("Hello!" ) class Greeter : def __call__ (self ): print ("Hi there!" ) print (callable (say_hello)) print (callable (42 )) print (callable (lambda x: x*2 )) greeter = Greeter() print (callable (greeter)) greeter()
2. 数学运算函数 abs() - 绝对值使者print (abs (-10 )) print (abs (3.14 )) print (abs (-2.5 )) print (abs (3 + 4j )) class Vector : def __init__ (self, x, y ): self .x = x self .y = y def __abs__ (self ): return (self .x**2 + self .y**2 )**0.5 v = Vector(3 , 4 ) print (abs (v))
round() - 四舍五入专家print (round (3.14159 )) print (round (3.14159 , 2 )) print (round (3.14159 , 3 )) print (round (2.5 )) print (round (3.5 )) print (round (4.5 )) print (round (-2.5 )) print (round (-3.5 ))
divmod() - 商和余数打包员result = divmod (10 , 3 ) print (result) print (f"商:{result[0 ]} , 余数:{result[1 ]} " )seconds = 3661 minutes, seconds_remain = divmod (seconds, 60 ) hours, minutes_remain = divmod (minutes, 60 ) print (f"{seconds} 秒 = {hours} 小时{minutes_remain} 分{seconds_remain} 秒" )print (divmod (10.5 , 3 ))
pow() - 幂运算大师print (pow (2 , 3 )) print (pow (2 , 3 , 5 )) print (pow (4 , 0.5 )) print (pow (27 , 1 /3 )) print (pow (2 , -2 ))
3. 序列操作函数 len() - 长度测量员print (len ("Hello" )) print (len ([1 , 2 , 3 , 4 ])) print (len ({"a" : 1 , "b" : 2 })) print (len ((1 , 2 , 3 ))) print (len (range (10 ))) class Playlist : def __init__ (self, songs ): self .songs = songs def __len__ (self ): return len (self .songs) my_playlist = Playlist(["Song1" , "Song2" , "Song3" ]) print (f"播放列表有{len (my_playlist)} 首歌" )
sorted() - 排序魔法师numbers = [3 , 1 , 4 , 1 , 5 , 9 , 2 ] print (sorted (numbers)) print (sorted (numbers, reverse=True )) words = ["apple" , "banana" , "cherry" , "date" ] print (sorted (words, key=len )) students = [ ("Alice" , 85 , 20 ), ("Bob" , 90 , 19 ), ("Charlie" , 85 , 21 ) ] print (sorted (students, key=lambda x: (-x[1 ], x[2 ])))
reversed() - 反转大师numbers = [1 , 2 , 3 , 4 , 5 ] print (list (reversed (numbers))) text = "Python" print ('' .join(reversed (text))) def is_palindrome (s ): return s == '' .join(reversed (s)) print (is_palindrome("racecar" )) print (is_palindrome("python" )) large_list = list (range (1_000_000 )) reversed_iter = reversed (large_list)
enumerate() - 编号小助手fruits = ["apple" , "banana" , "cherry" ] for index, fruit in enumerate (fruits): print (f"{index} : {fruit} " ) for index, fruit in enumerate (fruits, start=1 ): print (f"{index} . {fruit} " ) def find_all_positions (lst, target ): return [i for i, item in enumerate (lst) if item == target] numbers = [1 , 3 , 5 , 3 , 7 , 3 ] print (find_all_positions(numbers, 3 ))
zip() - 拉链缝合工names = ["Alice" , "Bob" , "Charlie" ] scores = [85 , 90 , 78 ] ages = [20 , 19 , 21 ] for name, score, age in zip (names, scores, ages): print (f"{name} : {score} 分, {age} 岁" ) score_dict = dict (zip (names, scores)) print (score_dict) list1 = [1 , 2 , 3 ] list2 = ['a' , 'b' ] print (list (zip (list1, list2))) pairs = [(1 , 'a' ), (2 , 'b' ), (3 , 'c' )] numbers, letters = zip (*pairs) print (numbers) print (letters)
filter() 和 map() - 数据转换双子星numbers = range (10 ) even_numbers = list (filter (lambda x: x % 2 == 0 , numbers)) print (f"偶数:{even_numbers} " ) mixed = [0 , 1 , False , 2 , '' , 3 , None ] truthy_values = list (filter (None , mixed)) print (f"真值:{truthy_values} " ) squares = list (map (lambda x: x**2 , range (5 ))) print (f"平方数:{squares} " ) list1 = [1 , 2 , 3 ] list2 = [10 , 20 , 30 ] sums = list (map (lambda x, y: x + y, list1, list2)) print (f"对应元素和:{sums} " ) prices = ["$10.5" , "$20.0" , "$15.75" ] clean_prices = list (map (lambda x: float (x.replace("$" , "" )), prices)) print (f"清洗后的价格:{clean_prices} " )
4. 输入输出函数 print() - 输出大总管print ("Hello, World!" )name = "Alice" age = 25 print ("姓名:" , name, "年龄:" , age) print ("Python" , "is" , "fun" , sep="-" , end="!\n" ) print (f"姓名:{name} ,年龄:{age} " ) print ("姓名:{},年龄:{}" .format (name, age)) with open ("output.txt" , "w" ) as f: print ("保存到文件" , file=f)
name = input ("请输入你的名字:" ) print (f"你好,{name} !" )age = int (input ("请输入你的年龄:" )) print (f"明年你就{age + 1 } 岁了!" )try : num1 = float (input ("请输入第一个数字:" )) num2 = float (input ("请输入第二个数字:" )) operation = input ("请输入操作符(+, -, *, /):" ) if operation == '+' : result = num1 + num2 elif operation == '-' : result = num1 - num2 elif operation == '*' : result = num1 * num2 elif operation == '/' : result = num1 / num2 else : result = "无效操作符" print (f"结果:{result} " ) except ValueError: print ("输入的不是有效数字!" )
5. 迭代和生成函数 range() - 数字序列生成器print (list (range (5 ))) print (list (range (2 , 6 ))) print (list (range (1 , 10 , 2 ))) print (list (range (5 , 0 , -1 ))) for i in range (3 ): print (f"第{i+1 } 次循环" ) fruits = ["apple" , "banana" , "cherry" ] for i in range (len (fruits)): print (f"{i} : {fruits[i]} " ) big_range = range (1_000_000 ) print (big_range[999999 ])
iter() 和 next() - 迭代控制双侠fruits = ["apple" , "banana" , "cherry" ] iterator = iter (fruits) print (next (iterator)) print (next (iterator)) print (next (iterator)) try : print (next (iterator)) except StopIteration: print ("没有更多元素了!" ) class CountDown : def __init__ (self, start ): self .current = start def __iter__ (self ): return self def __next__ (self ): if self .current <= 0 : raise StopIteration value = self .current self .current -= 1 return value for num in CountDown(3 ): print (num)
6. 属性操作函数 getattr(), setattr(), hasattr(), delattr() - 属性操作四剑客class Person : def __init__ (self, name, age ): self .name = name self .age = age person = Person("Alice" , 25 ) print (hasattr (person, "name" )) print (hasattr (person, "height" )) print (getattr (person, "name" )) print (getattr (person, "height" , 170 )) setattr (person, "height" , 165 )print (person.height) def say_hello (self ): print (f"Hello, I'm {self.name} " ) setattr (Person, "greet" , say_hello)person.greet() delattr (person, "height" )
vars() 和 dir() - 对象探秘工具class Example : def __init__ (self ): self .public = "公开属性" self ._protected = "受保护属性" self .__private = "私有属性" def method (self ): pass obj = Example() print (vars (obj)) print (dir (obj)[:10 ]) class A : def __init__ (self, x, y ): self .x = x self .y = y class B : def __init__ (self, x, y ): self .x = x self .y = y a = A(1 , 2 ) b = B(1 , 2 ) print (vars (a) == vars (b)) print (dir (a) == dir (b))
7. 编译执行函数 eval() 和 exec() - 动态代码执行者result = eval ("3 + 4 * 2" ) print (f"3 + 4 * 2 = {result} " ) x = 10 y = 20 result = eval ("x + y" , {"x" : 5 , "y" : 10 }) print (result) code = """ for i in range(3): print(f"第{i+1}次循环") """ exec (code)def safe_calculator (expression ): allowed_names = {"abs" : abs , "max" : max , "min" : min , "round" : round } try : return eval (expression, {"__builtins__" : {}}, allowed_names) except Exception as e: return f"错误:{e} " print (safe_calculator("abs(-5)" )) print (safe_calculator("max(1, 2, 3)" ))
8. 其他实用函数 open() - 文件操作门户with open ('example.txt' , 'r' , encoding='utf-8' ) as f: content = f.read() print (content) with open ('output.txt' , 'w' , encoding='utf-8' ) as f: f.write("Hello, World!\n" ) f.write("这是第二行" ) with open ('output.txt' , 'a' , encoding='utf-8' ) as f: f.write("\n这是追加的内容" ) with open ('example.txt' , 'r' , encoding='utf-8' ) as f: for line_number, line in enumerate (f, 1 ): print (f"第{line_number} 行: {line.strip()} " )
sum(), min(), max() - 统计三巨头numbers = [1 , 2 , 3 , 4 , 5 ] print (sum (numbers)) print (sum (numbers, 10 )) print (min (numbers)) print (max (numbers)) students = [ {"name" : "Alice" , "score" : 85 }, {"name" : "Bob" , "score" : 90 }, {"name" : "Charlie" , "score" : 78 } ] print (min (students, key=lambda s: s["score" ])) print (max (students, key=lambda s: s["score" ])) print (min (1 , 2 , 3 , 4 , 5 )) print (max (1.5 , 2.3 , 0.8 ))
any() 和 all() - 逻辑判断专家print (any ([False , False , True ])) print (any ([0 , "" , None , []])) print (all ([True , True , False ])) print (all ([1 , "hello" , [1 , 2 ]])) def is_valid_user_data (data ): required_fields = ["username" , "email" , "password" ] return all (field in data and data[field] for field in required_fields) user1 = {"username" : "alice" , "email" : "alice@example.com" , "password" : "123" } user2 = {"username" : "bob" , "email" : "" , "password" : "456" } print (is_valid_user_data(user1)) print (is_valid_user_data(user2))
四、总结与最佳实践 经过这次内置内容之旅,你应该已经掌握了Python中最强大的工具集。让我们回顾一下关键点:
使用内置函数的优势:
性能优越 :用C实现,比纯Python代码快得多
代码简洁 :一行内置函数可能替代多行循环
可靠稳定 :经过充分测试,无bug风险
可读性好 :Python开发者都能理解
实用小贴士: data = [5 , 2 , 8 , 1 , 9 , 3 ] result = sum (map (lambda x: x**2 , filter (lambda x: x % 2 == 0 , data))) print (f"偶数的平方和:{result} " )result = sum (x**2 for x in data if x % 2 == 0 ) print (f"使用生成器表达式:{result} " )from functools import reduceproduct = reduce(lambda x, y: x * y, range (1 , 6 )) print (f"5的阶乘:{product} " ) text = "Python is AWESOME!" result = ' ' .join(reversed (text.lower().split())) print (result)
最后提醒:
熟悉内置函数是成为Python高手的关键一步
善用help()和dir()探索未知领域
记住”Python之禅”:简单优于复杂,内置函数通常是最简单的解决方案
现在,你已经装备了Python内置函数的全套武器库,去编写更优雅、更高效的代码吧!记住,最好的代码往往是那些充分利用语言特性的代码。Happy coding!🐍✨