类装饰器致类被识别为函数的问题及文档URL优化方案
问题解决
一、修复装饰器导致类被识别为函数的问题
你的核心问题是装饰器返回了函数而非原类,导致inspect无法正确识别。只需修改装饰器逻辑,直接给类绑定URL属性并返回原类即可:
def test_url(url): def decorator(cls): # 给类添加存储测试链接的属性 cls.test_url = url # 关键:返回原类,而非替换成函数 return cls return decorator # 使用方式不变 @test_url("https://regex101.com/r/xxx") class SubRegex: def match(self, text): # 正则匹配逻辑 pass
这样inspect.isclass(SubRegex)会返回True,遍历模块时能正常识别为类,同时可以通过SubRegex.test_url获取对应的测试链接。
二、分离正则业务与文档URL的其他方案
如果不想用装饰器,还有几种更灵活的分离方式:
1. 显式注册映射
在模块单独区域维护类与URL的映射字典,完全隔离业务代码和文档链接:
# 正则业务类 class SubRegex: def match(self, text): pass class AnotherRegex: def match(self, text): pass # 单独的测试URL配置区 REGEX_TEST_LINKS = { SubRegex: "https://regex101.com/r/xxx", AnotherRegex: "https://regex101.com/r/yyy" } # 获取方式:REGEX_TEST_LINKS[SubRegex]
2. 类元数据注册函数
用单独的注册函数给类绑定URL,比装饰器更显式,不侵入类定义:
def register_test_url(cls, url): cls.test_url = url class SubRegex: def match(self, text): pass # 注册链接,放在类定义之后 register_test_url(SubRegex, "https://regex101.com/r/xxx")
3. 外部配置文件
把类名和URL的映射存在JSON/YAML等配置文件中,启动时加载并绑定到类:
// regex_test_links.json { "SubRegex": "https://regex101.com/r/xxx", "AnotherRegex": "https://regex101.com/r/yyy" }
加载逻辑:
import json from my_module import SubRegex, AnotherRegex with open("regex_test_links.json") as f: links = json.load(f) # 绑定到类 for cls_name, url in links.items(): cls = globals()[cls_name] cls.test_url = url
这种方式完全分离代码和配置,适合大量正则类的场景。
内容的提问来源于stack exchange,提问作者Daniele Tentoni
相关产品推荐
相关产品推荐

