Python隐藏的50个宝藏函数!99%的人都不知道的实用技巧!

你以为Python只有那些常见的内置函数?今天我要揭示Python鲜为人知的50个神秘函数,每一个都能让你的代码更优雅、更高效!这些函数连老手都不必定全知道!

Python隐藏的50个宝藏函数!99%的人都不知道的实用技巧!

⭐ 先点赞收藏,Python水平直线飙升!⭐

目录导航

一、进阶操作(12个)
二、系统交互(10个)
三、装饰器相关(8个)
四、元编程(10个)
五、性能工具(10个)


一、进阶操作函数(12个)

1. __import__()- 动态导入模块

python

# 动态导入模块
module_name = "math"
math_module = __import__(module_name)
print(math_module.sqrt(16))  # 4.0

# 动态导入包中的模块
datetime_module = __import__("datetime")
print(datetime_module.datetime.now())

# 实际应用:插件系统
def load_plugin(plugin_name):
    try:
        plugin = __import__(f"plugins.{plugin_name}", fromlist=[''])
        return plugin
    except ImportError:
        return None

2. iter()- 创建迭代器

python

# 创建列表迭代器
lst = [1, 2, 3]
it = iter(lst)
print(next(it))  # 1
print(next(it))  # 2
print(next(it))  # 3

# 创建自定义迭代器
class CountDown:
    def __init__(self, start):
        self.start = start
    
    def __iter__(self):
        self.current = self.start
        return self
    
    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        value = self.current
        self.current -= 1
        return value

for num in CountDown(5):
    print(num)  # 5 4 3 2 1

3. next()- 获取下一个元素

python

# 基本用法
numbers = iter([1, 2, 3])
print(next(numbers))  # 1
print(next(numbers))  # 2

# 提供默认值
numbers = iter([])
print(next(numbers, "没有更多元素"))  # "没有更多元素"

# 无限迭代器
import itertools
counter = itertools.count(1)
print(next(counter))  # 1
print(next(counter))  # 2

4. slice()- 创建切片对象

python

# 创建切片对象
my_slice = slice(1, 5, 2)
data = [0, 1, 2, 3, 4, 5, 6]
print(data[my_slice])  # [1, 3]

# 动态切片
def get_slice(data, start=None, stop=None, step=None):
    s = slice(start, stop, step)
    return data[s]

print(get_slice("Python", 1, 4))  # 'yth'

# 切片属性
s = slice(1, 10, 2)
print(s.start)   # 1
print(s.stop)    # 10
print(s.step)    # 2

5. memoryview()- 内存视图

python

# 创建内存视图
data = bytearray(b"Hello World")
mv = memoryview(data)

# 修改数据
mv[0] = 72  # 'H'
print(data)  # bytearray(b'Hello World')

# 切片不影响内存
slice_mv = mv[0:5]
print(bytes(slice_mv))  # b'Hello'

# 处理大文件高效读取
def process_large_file(filename):
    with open(filename, 'rb') as f:
        # 创建内存映射文件
        mv = memoryview(mmap(f.fileno(), 0, access=ACCESS_READ))
        # 高效处理
        process_chunk(mv[0:1024])

6. vars()- 对象属性字典

python

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

p = Person("Alice", 30)

# 获取对象属性字典
print(vars(p))  # {'name': 'Alice', 'age': 30}

# 修改属性
attrs = vars(p)
attrs['city'] = "New York"
print(p.city)  # New York

# 查看模块变量
import math
print(vars(math).keys())  # 查看math模块的所有变量

7. locals()- 局部变量字典

python

def show_locals():
    x = 10
    y = "hello"
    z = [1, 2, 3]
    print(locals())

show_locals()
# 输出:{'x': 10, 'y': 'hello', 'z': [1, 2, 3]}

# 动态创建局部变量
def dynamic_locals():
    local_vars = locals()
    for i in range(3):
        local_vars[f'var_{i}'] = i * 10
    print(locals())

dynamic_locals()

8. globals()- 全局变量字典

python

# 查看全局变量
x = 100
y = "global"

def show_globals():
    print(globals().keys())

# 动态添加全局变量
globals()['dynamic_var'] = "我是动态添加的"
print(dynamic_var)  # 我是动态添加的

# 修改模块行为
import sys
def custom_import():
    # 临时修改导入行为
    original_import = __builtins__.__import__
    # ...自定义逻辑
    pass

9. breakpoint()- 调试断点

python

def complex_calculation(data):
    result = 0
    for i, value in enumerate(data):
        # 设置断点
        if i == 5:
            breakpoint()  # 进入pdb调试器
        result += value * i
    return result

# 使用环境变量控制调试
# PYTHONBREAKPOINT=0 禁用断点
# PYTHONBREAKPOINT=pudb.set_trace 使用pudb调试器

10. ascii()- ASCII表明

python

# 将字符转换为ASCII表明
print(ascii("Hello"))        # 'Hello'
print(ascii("你好"))         # 'u4f60u597d'
print(ascii("Café"))         # 'Caf\xe9'

# 实际应用:安全输出
def safe_print(obj):
    """安全打印任何对象,避免编码问题"""
    print(ascii(obj))

safe_print("特殊字符: © ® ™")  # 安全输出

11. repr()vs ascii()对比

python

class SpecialString:
    def __init__(self, value):
        self.value = value
    
    def __repr__(self):
        return f"SpecialString({repr(self.value)})"

s = SpecialString("你好
世界")
print(repr(s))   # SpecialString('你好
世界')
print(ascii(s))  # SpecialString('u4f60u597d
u4e16u754c')

12. __build_class__()- 动态创建类

python

# 动态创建类
def init_method(self, name):
    self.name = name

def greet_method(self):
    return f"Hello, {self.name}!"

# 创建类字典
class_dict = {
    '__init__': init_method,
    'greet': greet_method,
    '__module__': '__main__'
}

# 动态创建类
Person = __build_class__(None, 'Person', (object,), class_dict)

# 使用动态创建的类
p = Person("Alice")
print(p.greet())  # Hello, Alice!

二、系统交互函数(10个)

13. open()的高级用法

python

# 多种模式组合
with open('data.txt', 'w+') as f:  # 读写模式,文件不存在则创建
    f.write("Hello
World
")
    f.seek(0)
    print(f.read())

# 编码处理
with open('file.txt', 'r', encoding='utf-8', errors='ignore') as f:
    content = f.read()

# 缓冲控制
with open('large.bin', 'rb', buffering=0) as f:  # 无缓冲
    data = f.read(1024)

14. exec()的高级应用

python

# 代码模板
template = """
def calculate_{operation}(a, b):
    return a {operator} b
"""

# 动态生成函数
operations = [
    ('add', '+'),
    ('subtract', '-'),
    ('multiply', '*'),
    ('divide', '/')
]

for name, op in operations:
    code = template.format(operation=name, operator=op)
    exec(code, globals())

print(calculate_add(10, 5))      # 15
print(calculate_multiply(3, 4))  # 12

15. compile()的三种模式

python

# 1. 'exec' 模式 - 编译代码块
code_block = """
x = 10
y = 20
result = x + y
"""
compiled_exec = compile(code_block, '<string>', 'exec')
exec(compiled_exec)
print(result)  # 30

# 2. 'eval' 模式 - 编译表达式
expression = "3 * 4 + 5"
compiled_eval = compile(expression, '<string>', 'eval')
print(eval(compiled_eval))  # 17

# 3. 'single' 模式 - 交互式单语句
single_stmt = "print('Hello from single mode')"
compiled_single = compile(single_stmt, '<string>', 'single')
exec(compiled_single)

16. eval()的安全用法

python

# 安全的环境
def safe_eval(expr, variables=None):
    """安全地评估表达式"""
    if variables is None:
        variables = {}
    
    # 限制可用的内置函数
    allowed_builtins = {
        'abs': abs,
        'max': max,
        'min': min,
        'sum': sum,
        'len': len,
        'range': range
    }
    
    # 创建安全命名空间
    namespace = {
        '__builtins__': allowed_builtins,
        **variables
    }
    
    return eval(expr, namespace)

# 安全使用
result = safe_eval("max(1, 2, 3) + len('hello')", {})
print(result)  # 8

17. staticmethod()- 静态方法

python

class MathUtils:
    @staticmethod
    def add(x, y):
        return x + y
    
    @staticmethod
    def factorial(n):
        if n <= 1:
            return 1
        return n * MathUtils.factorial(n - 1)

# 无需实例化即可调用
print(MathUtils.add(5, 3))        # 8
print(MathUtils.factorial(5))     # 120

# 可以作为普通函数使用
add_func = MathUtils.add
print(add_func(10, 20))           # 30

18. classmethod()- 类方法

python

class Person:
    population = 0
    
    def __init__(self, name):
        self.name = name
        Person.population += 1
    
    @classmethod
    def get_population(cls):
        return cls.population
    
    @classmethod
    def from_string(cls, string):
        """工厂方法:从字符串创建对象"""
        name, age = string.split(',')
        instance = cls(name.strip())
        instance.age = int(age.strip())
        return instance

# 使用类方法
p1 = Person("Alice")
p2 = Person("Bob")
print(Person.get_population())  # 2

# 使用工厂方法
p3 = Person.from_string("Charlie, 25")
print(p3.name, p3.age)  # Charlie 25

19. super()- 调用父类方法

python

class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        return "Some sound"

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)  # 调用父类初始化
        self.breed = breed
    
    def speak(self):
        parent_sound = super().speak()
        return f"{parent_sound}, but specifically: Woof!"

class Cat(Animal):
    def speak(self):
        return "Meow"

# 多重继承中的super
class A:
    def method(self):
        return "A"

class B(A):
    def method(self):
        return "B -> " + super().method()

class C(A):
    def method(self):
        return "C -> " + super().method()

class D(B, C):
    def method(self):
        return "D -> " + super().method()

print(D().method())  # D -> B -> C -> A
print(D.__mro__)     # 方法解析顺序

20. property()完整用法

python

class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius
    
    def get_celsius(self):
        print("获取摄氏度")
        return self._celsius
    
    def set_celsius(self, value):
        print("设置摄氏度")
        if value < -273.15:
            raise ValueError("温度不能低于绝对零度")
        self._celsius = value
    
    def get_fahrenheit(self):
        return self._celsius * 9/5 + 32
    
    def set_fahrenheit(self, value):
        self._celsius = (value - 32) * 5/9
    
    # 使用property函数
    celsius = property(get_celsius, set_celsius)
    fahrenheit = property(get_fahrenheit, set_fahrenheit)

temp = Temperature(25)
print(temp.celsius)      # 获取摄氏度 
 25
temp.celsius = 30        # 设置摄氏度
print(temp.fahrenheit)   # 86.0

21. hasattr()深入应用

python

class Configurable:
    def __init__(self):
        self._cache = {}
    
    def __getattr__(self, name):
        """处理不存在的属性"""
        if name in self._cache:
            return self._cache[name]
        elif name.startswith('default_'):
            return f"Default value for {name}"
        else:
            raise AttributeError(f"'{self.__class__.__name__}' 没有属性 '{name}'")
    
    def __setattr__(self, name, value):
        """拦截属性设置"""
        if name.startswith('_'):
            super().__setattr__(name, value)
        else:
            self._cache[name] = value

obj = Configurable()
obj.custom_value = "test"

print(hasattr(obj, 'custom_value'))    # True
print(hasattr(obj, 'default_color'))   # True(通过__getattr__)
print(hasattr(obj, 'nonexistent'))     # False

22. getattr()的默认值处理

python

class DataSource:
    def __init__(self):
        self.data = {
            'name': 'Alice',
            'age': 30,
            'city': 'Beijing'
        }
    
    def get(self, key, default=None):
        # 使用getattr风格
        return getattr(self, key, default)
    
    def __getattr__(self, name):
        """动态属性访问"""
        if name in self.data:
            return self.data[name]
        raise AttributeError(f"没有属性 '{name}'")

source = DataSource()

# 安全访问
print(getattr(source, 'name', '未知'))    # Alice
print(getattr(source, 'gender', '未知'))  # 未知

# 链式默认值
def deep_getattr(obj, attr_chain, default=None):
    """深度获取属性,支持点号分隔"""
    attrs = attr_chain.split('.')
    current = obj
    for attr in attrs:
        current = getattr(current, attr, None)
        if current is None:
            return default
    return current

三、装饰器相关函数(8个)

23. @functools.wraps- 保留元数据

python

import functools

def debug_decorator(func):
    @functools.wraps(func)  # 保留原函数信息
    def wrapper(*args, **kwargs):
        print(f"调用 {func.__name__} 参数: {args} {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} 返回: {result}")
        return result
    return wrapper

@debug_decorator
def add(a, b):
    """两数相加"""
    return a + b

print(add.__name__)   # add(而不是wrapper)
print(add.__doc__)    # 两数相加
print(add(2, 3))      # 带调试信息的调用

24. @functools.lru_cache- 缓存装饰器

python

import functools

@functools.lru_cache(maxsize=128)
def fibonacci(n):
    """计算斐波那契数列"""
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

# 第一次计算
print(fibonacci(30))  # 832040
print(fibonacci.cache_info())  # 查看缓存信息

@functools.lru_cache(maxsize=None)  # 无限缓存
def expensive_operation(x):
    print(f"计算 {x}...")
    return x ** 2

print(expensive_operation(5))  # 计算 5...
print(expensive_operation(5))  # 直接返回缓存结果

25. @functools.singledispatch- 单分派泛函数

python

import functools

@functools.singledispatch
def process(data):
    """默认处理器"""
    raise NotImplementedError(f"不支持的类型: {type(data)}")

@process.register(str)
def _(text):
    """处理字符串"""
    return f"字符串: {text.upper()}"

@process.register(list)
def _(lst):
    """处理列表"""
    return f"列表长度: {len(lst)}"

@process.register(dict)
def _(d):
    """处理字典"""
    return f"字典键: {', '.join(d.keys())}"

print(process("hello"))      # 字符串: HELLO
print(process([1, 2, 3]))    # 列表长度: 3
print(process({"a": 1}))     # 字典键: a

26. @contextlib.contextmanager- 上下文管理器

python

import contextlib

@contextlib.contextmanager
def timer():
    """计时上下文管理器"""
    import time
    start = time.time()
    try:
        yield
    finally:
        end = time.time()
        print(f"耗时: {end - start:.2f}秒")

@contextlib.contextmanager
def temporary_change(obj, attr, new_value):
    """临时修改属性"""
    old_value = getattr(obj, attr)
    setattr(obj, attr, new_value)
    try:
        yield
    finally:
        setattr(obj, attr, old_value)

# 使用示例
class Config:
    debug = False

config = Config()

with timer():
    import time
    time.sleep(1)

with temporary_change(config, 'debug', True):
    print(config.debug)  # True

print(config.debug)  # False(已恢复)

27. @dataclasses.dataclass- 数据类

python

from dataclasses import dataclass, field
import datetime

@dataclass(order=True)  # 生成比较方法
class Person:
    name: str
    birth_date: datetime.date
    email: str = field(default="")
    friends: list = field(default_factory=list, compare=False, repr=False)
    
    @property
    def age(self):
        today = datetime.date.today()
        return today.year - self.birth_date.year - (
            (today.month, today.day) < (self.birth_date.month, self.birth_date.day)
        )

# 自动生成 __init__, __repr__, __eq__ 等方法
p1 = Person("Alice", datetime.date(1990, 5, 15), "alice@email.com")
p2 = Person("Bob", datetime.date(1992, 3, 20))

print(p1)        # Person(name='Alice', birth_date=datetime.date(1990, 5, 15), email='alice@email.com')
print(p1.age)    # 计算年龄
print(p1 == p2)  # False

28. @typing.final- 最终装饰器

python

from typing import final

@final
class BaseClass:
    """标记为最终类,不能被继承"""
    pass

# 以下代码会报错
# class DerivedClass(BaseClass):
#     pass

class Parent:
    @final
    def cannot_override(self):
        """标记为最终方法,不能被子类重写"""
        return "原始实现"

class Child(Parent):
    # 以下代码会报错
    # def cannot_override(self):
    #     return "新的实现"
    pass

29. @abc.abstractmethod- 抽象方法

python

import abc

class Shape(abc.ABC):
    """抽象基类"""
    
    @abc.abstractmethod
    def area(self):
        """计算面积"""
        pass
    
    @abc.abstractmethod
    def perimeter(self):
        """计算周长"""
        pass
    
    @classmethod
    def __subclasshook__(cls, C):
        """自定义子类检查逻辑"""
        if cls is Shape:
            if any("area" in B.__dict__ for B in C.__mro__):
                return True
        return NotImplemented

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    
    def area(self):
        import math
        return math.pi * self.radius ** 2
    
    def perimeter(self):
        import math
        return 2 * math.pi * self.radius

# 使用抽象基类
circle = Circle(5)
print(circle.area())      # 78.54...
print(isinstance(circle, Shape))  # True

30. @staticmethodvs @classmethod对比

python

class Date:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day
    
    @classmethod
    def from_string(cls, date_string):
        """类方法:工厂方法"""
        year, month, day = map(int, date_string.split('-'))
        return cls(year, month, day)
    
    @staticmethod
    def is_leap_year(year):
        """静态方法:工具函数"""
        return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
    
    def __repr__(self):
        return f"{self.year}-{self.month:02d}-{self.day:02d}"

# 使用示例
date1 = Date(2023, 10, 1)
date2 = Date.from_string("2023-10-01")
print(Date.is_leap_year(2024))  # True

四、元编程函数(10个)

31. type()的三种用法

python

# 1. 查看类型
print(type(42))                # <class 'int'>

# 2. 动态创建类
# type(name, bases, dict)
MyClass = type('MyClass', (), {'x': 10})
obj = MyClass()
print(obj.x)                   # 10

# 3. 创建带方法的类
def say_hello(self):
    return f"Hello from {self.name}"

def init_method(self, name):
    self.name = name

Person = type('Person', (), {
    '__init__': init_method,
    'greet': say_hello,
    '__repr__': lambda self: f"Person({self.name})"
})

p = Person("Alice")
print(p.greet())               # Hello from Alice
print(p)                       # Person(Alice)

32. __subclasses__()- 获取子类

python

class Animal:
    pass

class Dog(Animal):
    pass

class Cat(Animal):
    pass

class PersianCat(Cat):
    pass

# 获取直接子类
print(Animal.__subclasses__())  # [<class '__main__.Dog'>, <class '__main__.Cat'>]

# 获取所有子类(递归)
def get_all_subclasses(cls):
    subclasses = []
    for subclass in cls.__subclasses__():
        subclasses.append(subclass)
        subclasses.extend(get_all_subclasses(subclass))
    return subclasses

print(get_all_subclasses(Animal))
# [<class '__main__.Dog'>, <class '__main__.Cat'>, <class '__main__.PersianCat'>]

33. mro()- 方法解析顺序

python

class A:
    def method(self):
        return "A"

class B(A):
    def method(self):
        return "B -> " + super().method()

class C(A):
    def method(self):
        return "C -> " + super().method()

class D(B, C):
    def method(self):
        return "D -> " + super().method()

# 查看MRO
print(D.__mro__)
# (<class '__main__.D'>, <class '__main__.B'>, 
#  <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)

d = D()
print(d.method())  # D -> B -> C -> A

34. __bases__- 父类元组

python

class Base1:
    pass

class Base2:
    pass

class Derived(Base1, Base2):
    pass

print(Derived.__bases__)         # (<class '__main__.Base1'>, <class '__main__.Base2'>)
print(Base1.__bases__)           # (<class 'object'>,)

# 动态修改继承关系
class NewBase:
    pass

Derived.__bases__ = (NewBase,)
print(Derived.__bases__)         # (<class '__main__.NewBase'>,)

35. __name__- 获取名称

python

# 模块名称
print(__name__)  # __main__(当直接执行时)

# 类名称
class MyClass:
    pass

print(MyClass.__name__)  # MyClass

# 函数名称
def my_function():
    pass

print(my_function.__name__)  # my_function

# 实际应用:日志记录
import logging

def log_call(func):
    def wrapper(*args, **kwargs):
        logging.info(f"调用 {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

36. __module__- 模块信息

python

class MyClass:
    pass

def my_function():
    pass

print(MyClass.__module__)      # __main__
print(my_function.__module__)  # __main__

# 跨模块引用
import math
print(math.sqrt.__module__)    # math

# 动态判断模块
def is_builtin(obj):
    return obj.__module__ == 'builtins'

print(is_builtin(len))        # True
print(is_builtin(MyClass))    # False

37. __dict__- 对象字典

python

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        return f"Hello, I'm {self.name}"

p = Person("Alice", 30)

# 查看实例字典
print(p.__dict__)  # {'name': 'Alice', 'age': 30}

# 查看类字典
print(Person.__dict__.keys())
# dict_keys(['__module__', '__init__', 'greet', '__dict__', ...])

# 动态添加方法
def new_method(self):
    return f"New method for {self.name}"

Person.new_method = new_method
print(p.new_method())  # New method for Alice

38. __class__- 获取类对象

python

class Animal:
    def identify(self):
        return f"I am a {self.__class__.__name__}"

class Dog(Animal):
    pass

dog = Dog()
print(dog.__class__)           # <class '__main__.Dog'>
print(dog.__class__.__name__)  # Dog

# 动态创建实例
def create_instance(cls_name, *args, **kwargs):
    """根据类名创建实例"""
    import sys
    cls = getattr(sys.modules[__name__], cls_name)
    return cls(*args, **kwargs)

new_dog = create_instance('Dog')
print(new_dog.identify())      # I am a Dog

39. __annotations__- 类型注解

python

# 函数注解
def greet(name: str, times: int = 1) -> str:
    return f"Hello {name}! " * times

print(greet.__annotations__)
# {'name': <class 'str'>, 'times': <class 'int'>, 'return': <class 'str'>}

# 类属性注解
class Point:
    x: float
    y: float
    
    def __init__(self, x: float, y: float):
        self.x = x
        self.y = y

print(Point.__annotations__)  # {'x': <class 'float'>, 'y': <class 'float'>}

# 变量注解
count: int = 0
print(__annotations__)  # {'count': <class 'int'>}

40. __slots__- 限制属性

python

class PersonWithSlots:
    __slots__ = ('name', 'age', '__weakref__')
    
    def __init__(self, name, age):
        self.name = name
        self.age = age

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

# 对比内存使用
import sys

p1 = PersonWithSlots("Alice", 30)
p2 = PersonWithoutSlots("Bob", 30)

print(sys.getsizeof(p1))  # 较小
print(sys.getsizeof(p2))  # 较大

# slots限制动态添加属性
try:
    p1.city = "Beijing"  # 报错:AttributeError
except AttributeError as e:
    print(f"错误: {e}")

五、性能工具函数(10个)

41. timeit()- 性能测试

python

import timeit

# 测试代码执行时间
setup_code = "import math"
test_code = "math.sqrt(10000)"

time = timeit.timeit(test_code, setup=setup_code, number=1000000)
print(f"执行100万次耗时: {time:.3f}秒")

# 测试多个实现
def method1():
    return sum(range(1000))

def method2():
    return 1000 * 999 // 2

time1 = timeit.timeit(method1, number=10000)
time2 = timeit.timeit(method2, number=10000)

print(f"方法1: {time1:.6f}秒")
print(f"方法2: {time2:.6f}秒")
print(f"速度提升: {time1/time2:.1f}倍")

42. profile()- 性能分析

python

import cProfile
import pstats

def slow_function():
    total = 0
    for i in range(10000):
        for j in range(100):
            total += i * j
    return total

def fast_function():
    n = 10000
    return n * (n-1) * 100 // 2

# 性能分析
profiler = cProfile.Profile()
profiler.enable()

slow_function()
fast_function()

profiler.disable()

# 输出分析结果
stats = pstats.Stats(profiler)
stats.strip_dirs().sort_stats('time').print_stats(10)

43. dis()- 字节码反汇编

python

import dis

def example_function(x):
    if x > 0:
        return x * 2
    else:
        return -x

# 查看字节码
print("=== 函数字节码 ===")
dis.dis(example_function)

# 查看具体操作
print("
=== 字节码详情 ===")
code_obj = example_function.__code__
print(f"参数数量: {code_obj.co_argcount}")
print(f"局部变量: {code_obj.co_varnames}")
print(f"常量: {code_obj.co_consts}")

44. inspect模块函数

python

import inspect

def example(a: int, b: int = 10, *args, **kwargs) -> int:
    """示例函数"""
    return a + b

# 获取源码
print("源码:")
print(inspect.getsource(example))

# 获取签名
sig = inspect.signature(example)
print("
签名:")
print(sig)

# 参数信息
print("
参数详情:")
for param in sig.parameters.values():
    print(f"  {param.name}: {param.annotation} = {param.default}")

# 调用栈信息
def show_stack():
    frame = inspect.currentframe()
    print("
调用栈:")
    for frame_info in inspect.getouterframes(frame):
        print(f"  文件: {frame_info.filename}, 行: {frame_info.lineno}")

45. sys.getsizeof()- 内存大小

python

import sys

# 不同数据类型的内存占用
data_types = [
    42,
    3.14159,
    "Hello World",
    [1, 2, 3, 4, 5],
    {'a': 1, 'b': 2, 'c': 3},
    {1, 2, 3, 4, 5},
    (1, 2, 3, 4, 5)
]

print("各数据类型内存占用:")
for item in data_types:
    size = sys.getsizeof(item)
    print(f"  {type(item).__name__:10} {str(item)[:30]:30} {size:6} 字节")

# 计算总内存
def total_size(obj, seen=None):
    """递归计算对象总内存"""
    if seen is None:
        seen = set()
    
    obj_id = id(obj)
    if obj_id in seen:
        return 0
    
    seen.add(obj_id)
    size = sys.getsizeof(obj)
    
    if isinstance(obj, dict):
        size += sum(total_size(k, seen) + total_size(v, seen) for k, v in obj.items())
    elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
        size += sum(total_size(item, seen) for item in obj)
    
    return size

nested_dict = {'a': [1, 2, 3], 'b': {'x': 10, 'y': [4, 5, 6]}}
print(f"
嵌套字典总内存: {total_size(nested_dict)} 字节")

46. gc模块函数

python

import gc

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None
    
    def __del__(self):
        print(f"删除节点: {self.value}")

# 创建循环引用
node1 = Node(1)
node2 = Node(2)
node1.next = node2
node2.next = node1

# 垃圾回收统计
print("垃圾回收统计:")
print(gc.get_count())
print(gc.get_stats())

# 手动触发垃圾回收
print("
手动触发垃圾回收:")
gc.collect()
print(f"回收对象数: {gc.collect()}")

# 调试内存泄漏
gc.set_debug(gc.DEBUG_STATS | gc.DEBUG_LEAK)

47. tracemalloc- 内存跟踪

python

import tracemalloc

def memory_intensive():
    """内存密集型操作"""
    data = []
    for i in range(10000):
        data.append([j for j in range(1000)])
    return data

# 开始跟踪
tracemalloc.start()

# 执行操作
result = memory_intensive()

# 获取快照
snapshot = tracemalloc.take_snapshot()

# 分析内存使用
print("内存使用最多的10个对象:")
top_stats = snapshot.statistics('lineno')
for stat in top_stats[:10]:
    print(stat)

# 停止跟踪
tracemalloc.stop()

48. itertools高级迭代

python

import itertools

# 无限迭代器
print("计数:", list(itertools.islice(itertools.count(10), 5)))  # [10, 11, 12, 13, 14]
print("循环:", list(itertools.islice(itertools.cycle('ABC'), 7)))  # ['A', 'B', 'C', 'A', 'B', 'C', 'A']

# 排列组合
print("排列:", list(itertools.permutations('ABC', 2)))  # [('A', 'B'), ('A', 'C'), ('B', 'A'), ...]
print("组合:", list(itertools.combinations('ABCD', 3)))  # [('A', 'B', 'C'), ('A', 'B', 'D'), ...]

# 分组
data = sorted(['apple', 'banana', 'cherry', 'date', 'elderberry'], key=len)
for key, group in itertools.groupby(data, key=len):
    print(f"长度{key}: {list(group)}")

# 链式操作
chain = itertools.chain('ABC', 'DEF')
print("链式:", list(chain))  # ['A', 'B', 'C', 'D', 'E', 'F']

49. functools高阶函数

python

import functools

# partial 函数 - 固定部分参数
def power(base, exponent):
    return base ** exponent

square = functools.partial(power, exponent=2)
cube = functools.partial(power, exponent=3)

print(f"5的平方: {square(5)}")  # 25
print(f"3的立方: {cube(3)}")    # 27

# reduce 函数 - 累积计算
numbers = [1, 2, 3, 4, 5]
product = functools.reduce(lambda x, y: x * y, numbers)
print(f"连乘积: {product}")  # 120

# total_ordering - 自动生成比较方法
import math
from functools import total_ordering

@total_ordering
class Angle:
    def __init__(self, degrees):
        self.degrees = degrees % 360
    
    def __eq__(self, other):
        return self.degrees == other.degrees
    
    def __lt__(self, other):
        return self.degrees < other.degrees
    
    def __repr__(self):
        return f"Angle({self.degrees}°)"

a1, a2 = Angle(30), Angle(390)
print(a1 == a2)  # True
print(a1 < Angle(90))  # True

50. contextlib上下文工具

python

import contextlib

# 多个上下文管理器
with contextlib.ExitStack() as stack:
    files = [
        stack.enter_context(open(f'file{i}.txt', 'w'))
        for i in range(3)
    ]
    for i, f in enumerate(files):
        f.write(f"文件{i}的内容
")

# 抑制异常
with contextlib.suppress(FileNotFoundError):
    with open('nonexistent.txt') as f:
        content = f.read()

# 重定向输出
import io
output = io.StringIO()
with contextlib.redirect_stdout(output):
    print("这不会显示在控制台")
    print("而是被重定向到字符串")

print(f"捕获的输出: {output.getvalue()}")

# 上下文装饰器工厂
@contextlib.contextmanager
def log_context(name):
    print(f"进入上下文: {name}")
    try:
        yield
    finally:
        print(f"离开上下文: {name}")

with log_context("测试"):
    print("执行操作")

综合实战项目

项目:智能配置管理器

python

import functools
import contextlib
import inspect
from typing import Any, Dict
from dataclasses import dataclass, field

@dataclass
class Config:
    """配置管理类"""
    debug: bool = False
    log_level: str = "INFO"
    timeout: int = 30
    retry_times: int = 3
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]):
        """从字典创建配置"""
        valid_fields = set(cls.__annotations__.keys())
        filtered = {k: v for k, v in data.items() if k in valid_fields}
        return cls(**filtered)
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {k: getattr(self, k) for k in self.__annotations__}

class ConfigManager:
    """智能配置管理器"""
    
    def __init__(self):
        self._config = Config()
        self._history = []
        self._cache = {}
    
    @contextlib.contextmanager
    def temporary_config(self, **kwargs):
        """临时修改配置的上下文管理器"""
        old_values = {}
        for key, value in kwargs.items():
            if hasattr(self._config, key):
                old_values[key] = getattr(self._config, key)
                setattr(self._config, key, value)
        try:
            yield
        finally:
            for key, value in old_values.items():
                setattr(self._config, key, value)
    
    @functools.lru_cache(maxsize=128)
    def compute_value(self, func_name: str, *args):
        """缓存计算结果"""
        if func_name == 'complex_calc':
            import math
            return math.prod(args) ** 2
    
    def __getattr__(self, name):
        """动态属性访问"""
        if name in self._config.__annotations__:
            return getattr(self._config, name)
        raise AttributeError(f"ConfigManager没有属性'{name}'")
    
    def __dir__(self):
        """增强dir()输出"""
        base = super().__dir__()
        config_attrs = list(self._config.__annotations__.keys())
        return sorted(set(base + config_attrs))

# 使用示例
manager = ConfigManager()

print(f"当前配置: {manager._config}")

with manager.temporary_config(debug=True, timeout=60):
    print(f"临时配置: {manager._config}")
    result = manager.compute_value('complex_calc', 2, 3, 4)
    print(f"计算结果: {result}")

print(f"恢复配置: {manager._config}")

函数分类总结

text

 系统交互类:
  __import__, open, exec, eval, compile, breakpoint

 迭代器类:
  iter, next, slice, enumerate, zip, reversed

 内省类:
  vars, locals, globals, type, isinstance, issubclass
  callable, hasattr, getattr, setattr, delattr

 装饰器类:
  staticmethod, classmethod, property, super
  functools.wraps, functools.lru_cache

⚡ 性能工具类:
  memoryview, sys.getsizeof, timeit, profile, dis
  gc.collect, tracemalloc

 元编程类:
  __build_class__, __subclasses__, __mro__, __bases__
  __name__, __module__, __dict__, __class__, __annotations__
  __slots__

学习提议

初级:掌握前30个函数,能解决90%的日常问题
中级:学习元编程函数,理解Python运行机制
高级:精通性能工具,写出高效优雅的代码

实战路线

  1. 先尝试修改现有代码,用这些函数优化
  2. 创建自己的工具库,封装常用功能
  3. 参与开源项目,学习别人的优秀实践
  4. 尝试实现一个简单的ORM或Web框架

如果觉得有用,请务必:

  1. 点赞支持原创
  2. 关注获取更多Python深度内容
  3. 分享给你的团队和好友
  4. 评论你最喜爱的函数或提出疑问

下期预告:Python设计模式实战:23种模式完整实现!

© 版权声明

相关文章

暂无评论

none
暂无评论...