delattr()函数是setattr()的配套函数,用于动态删除对象属性。
class User:
def __init__(self, name, age, email):
self.name = name
self.age = age
self.email = email
# 创建用户实例
user = User("张三", 25, "zhang@example.com")
print(f"删除前属性: {user.__dict__}")
# 删除email属性
delattr(user, 'email')
print(f"删除后属性: {user.__dict__}")
# 等价于直接使用del
del user.age
print(f"最终属性: {user.__dict__}")为什么__dict__可以查看实例的属性可以看这篇:
Python 世界的"三层身份证":__dict__的魔法与秘密
class ConfigManager:
def __init__(self):
self._config = {
'debug_mode': True,
'log_level': 'INFO',
'max_connections': 100
}
# 将配置项设置为实例属性
for key, value in self._config.items():
setattr(self, key, value)
def remove_config(self, key):
"""安全删除配置项"""
if hasattr(self, key):
delattr(self, key)
print(f"已删除配置: {key}")
else:
print(f"配置项不存在: {key}")
def cleanup_temp_attrs(self):
"""清理临时属性"""
temp_attrs = [attr for attr in dir(self)
if attr.startswith('_temp_')]
for attr in temp_attrs:
delattr(self, attr)
print(f"清理临时属性: {attr}")
# 使用示例
config = ConfigManager()
print(f"初始配置: {config.debug_mode}")
# 动态添加临时属性
config._temp_cache = "临时数据"
config.remove_config('debug_mode')
config.cleanup_temp_attrs()dict()函数提供了三种灵活的方式来创建字典:
# 方式1:关键字参数创建
person1 = dict(name="李四", age=30, city="北京")
print(f"关键字创建: {person1}")
# 方式2:从映射对象创建
from collections import OrderedDict
ordered_dict = OrderedDict([('name', '王五'), ('age', 25)])
person2 = dict(ordered_dict)
print(f"映射创建: {person2}")
# 方式3:从可迭代对象创建
items = [('name', '赵六'), ('age', 28), ('city', '上海')]
person3 = dict(items)
print(f"可迭代创建: {person3}")
# 方式4:组合使用
person4 = dict([('name', '钱七')], age=35, city="广州")
print(f"组合创建: {person4}")class ConfigBuilder:
@staticmethod
def merge_configs(*configs):
"""合并多个配置字典"""
result = dict()
for config in configs:
if isinstance(config, dict):
result.update(config)
elif hasattr(config, '__iter__'):
result.update(dict(config))
return result
@staticmethod
def create_from_env_vars(env_vars):
"""从环境变量列表创建配置"""
# 模拟环境变量:KEY=VALUE格式
env_pairs = [env.split('=') for env in env_vars if '=' in env]
return dict(env_pairs)
@staticmethod
def normalize_config(config_data):
"""标准化配置数据"""
if isinstance(config_data, dict):
return config_data
elif hasattr(config_data, '_asdict'): # 命名元组
return dict(config_data._asdict())
elif isinstance(config_data, (list, tuple)):
return dict(config_data)
else:
raise ValueError("不支持的配置格式")
# 使用示例
default_config = {'debug': False, 'port': 8080}
user_config = [('debug', True), ('host', 'localhost')]
env_config = ['DB_HOST=localhost', 'DB_PORT=5432']
# 合并配置
final_config = ConfigBuilder.merge_configs(
default_config,
user_config,
ConfigBuilder.create_from_env_vars(env_config)
)
print(f"最终配置: {final_config}")dir()函数是Python自省的重要工具,可以查看对象的可用属性和方法。
import math
# 查看当前作用域的名称
print("当前作用域名称:")
current_names = [name for name in dir() if not name.startswith('_')]
print(current_names[:5]) # 显示前5个
# 查看模块的属性
print("\nmath模块的部分函数:")
math_functions = [name for name in dir(math)
if not name.startswith('_') and callable(getattr(math, name))]
print(math_functions[:8]) # 显示前8个函数
# 查看自定义对象的属性
class SmartDevice:
def __init__(self, name, status=False):
self.name = name
self._status = status
def turn_on(self):
self._status = True
def turn_off(self):
self._status = False
def __dir__(self):
"""自定义dir()输出"""
return ['name', 'status', 'turn_on', 'turn_off', 'is_active']
device = SmartDevice("智能灯")
print(f"\n设备属性: {dir(device)}")class APIExplorer:
def __init__(self, target_object):
self.target = target_object
def explore_methods(self):
"""探索对象的方法"""
methods = [name for name in dir(self.target)
if callable(getattr(self.target, name))
and not name.startswith('_')]
return methods
def explore_properties(self):
"""探索对象的属性"""
properties = [name for name in dir(self.target)
if not callable(getattr(self.target, name))
and not name.startswith('_')]
return properties
def get_method_signature(self, method_name):
"""获取方法签名信息"""
try:
method = getattr(self.target, method_name)
return {
'name': method_name,
'callable': callable(method),
'module': getattr(method, '__module__', 'Unknown'),
'doc': getattr(method, '__doc__', 'No documentation')
}
except AttributeError:
return None
def generate_api_docs(self):
"""生成简单的API文档"""
print(f"=== {self.target.__class__.__name__} API ===")
print("\n方法:")
for method in self.explore_methods()[:5]: # 只显示前5个
info = self.get_method_signature(method)
if info:
print(f" {info['name']} - {info['doc'][:50]}...")
print("\n属性:")
for prop in self.explore_properties()[:5]: # 只显示前5个
print(f" {prop}")
# 使用示例:探索list类型
explorer = APIExplorer([])
explorer.generate_api_docs()divmod()函数返回商和余数组成的元组,特别适合需要同时使用两种结果的场景。
# 整数除法
result = divmod(10, 3)
print(f"10除以3: 商={result[0]}, 余数={result[1]}")
# 浮点数除法
float_result = divmod(10.5, 3.2)
print(f"10.5除以3.2: 商={float_result[0]:.2f}, 余数={float_result[1]:.2f}")
# 等价于
a, b = 10, 3
manual_result = (a // b, a % b)
print(f"手动计算: {manual_result}")class Calculator:
@staticmethod
def seconds_to_hms(total_seconds):
"""将秒数转换为小时:分钟:秒格式"""
hours, remainder = divmod(total_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
return hours, minutes, seconds
@staticmethod
def calculate_pagination(total_items, items_per_page):
"""计算分页信息"""
total_pages, remainder = divmod(total_items, items_per_page)
if remainder > 0:
total_pages += 1
return total_pages
@staticmethod
def money_breakdown(total_cents):
"""将金额分解为元、角、分"""
yuan, remainder = divmod(total_cents, 100)
jiao, fen = divmod(remainder, 10)
return yuan, jiao, fen
@staticmethod
def coordinate_conversion(total_units, base_unit):
"""坐标单位转换"""
major_units, minor_units = divmod(total_units, base_unit)
return major_units, minor_units
# 使用示例
calc = Calculator()
# 时间转换
seconds = 3665
hours, minutes, seconds = calc.seconds_to_hms(seconds)
print(f"{seconds}秒 = {hours}小时{minutes}分钟{seconds}秒")
# 分页计算
total_items = 105
items_per_page = 10
pages = calc.calculate_pagination(total_items, items_per_page)
print(f"{total_items}个项目,每页{items_per_page}个,需要{pages}页")
# 金额分解
total_cents = 1234
yuan, jiao, fen = calc.money_breakdown(total_cents)
print(f"{total_cents}分 = {yuan}元{jiao}角{fen}分")通过今天的探索,我们深入了解了四个强大的内置函数:
阅读推荐:
✨关注我,获取更多Python学习资源、实战项目和行业动态!在公众号后台回复"python学习",获取Python学习电子书籍!