[英]Decorating with arguments a Class Declaration
I'm trying to create a Class representing a regex to execute for my application.我正在尝试创建一个 Class 表示要为我的应用程序执行的正则表达式。 For each regex I have a link to the regex101.com page where users can find unit tests.
对于每个正则表达式,我都有一个指向 regex101.com 页面的链接,用户可以在其中找到单元测试。 I wanna use this solution to have near the class declaration this link but without having them in the class code.
我想使用这个解决方案在 class 声明附近有这个链接,但没有在 class 代码中。 The code I think about has to look like this:
我想到的代码必须如下所示:
class TestUrl(object):
def __init__(self, url) -> None:
self.url = url
def __call__(self, cls) -> Any:
functools.update_wrapper(self, cls)
cls.url = self.url
def wrapper(*args: Any, **kwds: Any):
return cls(*args, **kwds)
return wrapper
def test_url(url):
def wrapper_class(cls):
cls.test_url = url
@functools.wraps(cls)
def wrapper(*args, **kwargs):
return cls(*args, **kwargs)
return wrapper
return wrapper_class
class Regex:
def __init__(self, pattern, repl, flags) -> None:
self.exp = re.compile(pattern, flags=flags)
self.repl = repl
self.flags = flags
def sub(self, string: str):
return self.exp.sub(self.repl, string)
@test_url("https://regex101.com/r/.../...")
class SubRegex(Regex):
def __init__(self):
super().__init__(r'...', r'...', re.MULTILINE | re.DOTALL)
But my problem is that when I wanns cycle on all classes in the module using this code:但我的问题是,当我想使用这段代码循环模块中的所有类时:
def test_all_regexs(regex):
module = importlib.import_module("...")
print(f"Looking at {module}")
for name, obj in inspect.getmembers(module):
if inspect.isclass(obj):
print(f"Class: {name}, {obj}")
if inspect.isfunction(obj):
print(f"Func: {name}, {obj}")
The output is always: output 始终是:
Func: SubRegex, <function SubRegex at ...>
Class: Regex, <class '....Regex'>
Class: TestUrl, <class '....TestUrl'>
Func: test_url, <function test_url at ...>
I can't figure out how obtain SubRegex as Class, not as Func.我不知道如何将 SubRegex 获取为 Class,而不是 Func。 How can I get this?
我怎样才能得到这个?
PS: Do you have another way to don't mix application logic like regex patterns with the url I use only for documentation? PS:您是否有另一种方法可以避免将正则表达式模式之类的应用程序逻辑与我仅用于文档的 url 混合使用?
Your decorator shouldn't define a new function (or even a new class) to return (or even a new class).你的装饰器不应该定义一个新的 function (或者甚至是一个新类)来返回(或者甚至是一个新类)。 It should simply update
cls
in-place, then return cls
itself.它应该简单地就地更新
cls
,然后返回cls
本身。
def test_url(url):
def wrapper(cls):
cls.test_url = url
return cls
return wrapper
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.