发布于2026-07-01 阅读(0)
扫一扫,手机访问
摘要:本文介绍如何利用 Python 元类(metaclass)实现类属性访问,探讨如何基于这一机制实现单例模式,并进一步延伸为“服务端模式”,实现 类名.single.xxx 的优雅调用方式,同时支持 IDE 类型提示和代码补全。

在 Python 中,对象可以拥有属性,通过 @property 装饰器就能轻松搞定。那么,类能不能也拥有属性?当然可以。这篇文章要聊的,就是如何通过元类(metaclass)来实现这一点,并把它玩出花来——比如,做成一个优雅的服务调度工具。
元类是什么?简单说,它是“类的类”。当你定义一个类并指定 metaclass=Meta 时,Python 会用 Meta 来创建这个类的实例。既然我们能在元类里定义 @property,那当然就能让“类本身”拥有属性访问的能力。
from functools import lru_cache
class Meta(type):
@property
def test(cls) -> str:
"""测试属性"""
if not hasattr(cls, '__test__'):
cls.__test__ = 'test'
return cls.__test__
@test.setter
def test(cls, value: str):
cls.__test__ = value
@property
@lru_cache(maxsize=1)
def single(cls):
"""单例属性"""
return cls()
class MyClass(metaclass=Meta):
single: 'MyClass' # 类型注解
def __init__(self):
print('init')
self.abc = 'abc'
# 使用方式
MyClass.test = 'test2' # 设置属性
print(MyClass.test) # 输出: test2
print(MyClass.single.abc) # 输出: abc
| 部分 | 说明 |
|---|---|
Meta(type) | 继承 type,成为元类 |
@property def test | 为类定义只读属性 test |
@test.setter | 定义属性 setter,支持 MyClass.test = value |
@property @lru_cache def single | 为类定义单例属性,使用缓存确保只创建一个实例 |
single: 'MyClass' | 类型注解,让 IDE 知道 single 返回 MyClass 类型 |
类名.single 即可获取单例在大型项目中,不同模块之间经常需要相互调用服务。如果直接用 get_db() 函数或 Database() 构造函数,常常会遇到几个头疼的问题:
服务端模式就是冲着解决这些问题来的:
# 访问方式:类名.single.方法()
UserService.single.get_user(123)
ConfigService.single.get('database.host')
是不是清爽多了?
from functools import lru_cache
from typing import TypeVar, Generic
class Meta(type):
"""服务端元类"""
@property
@lru_cache(maxsize=None)
def single(cls):
"""获取单例实例(延迟创建)"""
return cls()
class Service(metaclass=Meta):
"""服务基类"""
pass
# 定义用户服务
class UserService(Service):
single: 'UserService' # IDE 类型提示
def __init__(self):
# 模拟初始化(如连接数据库)
print('UserService 初始化')
self._cache = {}
def get_user(self, user_id: int) -> dict:
"""获取用户信息"""
if user_id not in self._cache:
self._cache[user_id] = {'id': user_id, 'name': f'User_{user_id}'}
return self._cache[user_id]
# 定义配置服务
class ConfigService(Service):
single: 'ConfigService'
def __init__(self):
print('ConfigService 初始化')
self._config = {'database': {'host': 'localhost', 'port': 3306}}
def get(self, key: str, default=None):
"""获取配置值"""
keys = key.split('.')
value = self._config
for k in keys:
if isinstance(value, dict) and k in value:
value = value[k]
else:
return default
return value
# 使用方式
if __name__ == '__main__':
# 首次访问时创建实例
user = UserService.single.get_user(123)
print(user)
# 再次访问返回同一实例
user2 = UserService.single.get_user(456)
# 配置服务
host = ConfigService.single.get('database.host')
print(f'数据库地址: {host}')
UserService 初始化
{'id': 123, 'name': 'User_123'}
{'id': 456, 'name': 'User_456'}
数据库地址: localhost
可以看到,每个服务只在第一次被访问时初始化,之后拿到的都是同一个实例。这背后,lru_cache 默默扛下了所有。
虽然说 single 返回的是类实例本身,但 Python 默认并不知道 single 具体返回哪种类型。这就导致了:
class UserService(Service):
single: 'UserService' # 类型注解,告诉 IDE single 返回 UserService
这就是字符串形式的类型注解(Forward Reference),Python 会在运行时把它解析成实际的类型。
from typing import Protocol
class IBusiness(Protocol):
'''业务逻辑接口'''
def start(self, url: str) -> None:
'''开始爬取操作. 在新线程中执行.'''
def stop(self) -> None:
'''停止爬取链接'''
class UserService(Service):
single: 'IBusiness' # 类型注解,告诉 IDE single 返回 UserService
有了类型注解后,事情就顺多了:
UserService.single. 后面的方法说白了,这就是为了让写代码的人少掉几根头发。
| 内容 | 说明 |
|---|---|
| 元类属性 | 通过 Meta(type) 和 @property 实现类属性访问 |
| 服务端模式 | 类名.single.方法() 方式调用服务 |
| 类型注解 | single: '类名' 让 IDE 支持代码补全 |
| 延迟初始化 | 访问时创建实例,避免循环依赖 |
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8