如何解决Python 键入将字符串附加到类成员
假设我有一个这样的类型提示类:
class Foo:
one: str
two: int
three: str
是否可以声明一个类型,使其具有与 Foo
相同的属性,但具有例如_a
附加到静态类型检查器可见的末尾?即
class Bar:
one_a: str
two_a: int
three_a: str
换句话说,我想单独声明 Foo
,然后自动生成类型 Bar
,以便 Bar
类型的任何变量都有 one_a
等。在代码完成期间出现。来自 TypeScript 背景,这很容易实现,但我不确定 Python 的类型系统是否具有足够的表现力。
解决方法
我不知道这是否会让它们像您想要的那样在代码完成期间出现,因为这取决于您的 IDE 的智能程度,但这里是如何使用元类将所需的类型提示注释添加到另一个班级:
class MyMetaClass(type):
""" Create class that with annotations from a template class whose
name have all had a suffix added to them.
"""
def __new__(metaclass,classname,bases,classdict):
_template = classdict.get('_template',None)
_suffix = classdict.get('_suffix',None)
if not (_template and _suffix):
raise RuntimeError(f'_template or _suffix not defined in class {classname!r}')
__annotations__ = {name+_suffix: type
for name,type in _template.__annotations__.items()}
classdict['__annotations__'] = __annotations__
return type.__new__(metaclass,classdict)
class Foo:
one: str
two: int
three: str
class Bar(metaclass=MyMetaClass):
_template = Foo
_suffix = '_a'
print(f'{Bar.__annotations__}') # -> {'one_a': <class 'str'>,'two_a': <class 'int'>,'three_a': <class 'str'>}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。