考虑用Python编写一个接口类。该接口将 getter 和 setter 方法隐藏在属性后面。有几个属性具有非常相似的结构,只是名称不同。为了减少代码重复,该接口对其属性使用工厂方法:
from __future__ import annotations
class Interface:
def property_factory(name: str) -> property:
"""Create a property depending on the name."""
@property
def _complex_property(self: Interface) -> str:
# Do something complex with the provided name
return name
@_complex_property.setter
def _complex_property(self: Interface, _: str):
pass
return _complex_property
foo = property_factory("foo") # Works just like an actual property
bar = property_factory("bar")
def main():
interface = Interface()
interface.foo # Is of type '(variable) foo: Any' instead of '(property) foo: str'
if __name__ == "__main__":
main()
此实现的一个问题是
Interface.foo
和 Interface.bar
将被标记为 (variable) foo/bar: Any
,即使它们应该是 (property) foo/bar: str
。有没有办法正确输入提示 foo 和 bar?
使用内联类型提示,如
foo: str = property_factory("foo")
感觉有误导性,因为 foo 并不是真正的字符串。
我对这种属性模式并没有死心塌地。如果有更好的方法来创建属性,我也很乐意更改它。但是,请记住,接口需要属性,因为实际代码在 getter/setter 方法中执行更复杂的操作。另外,我想保留属性,而不是像 get_property(self, name: str) 这样的通用方法。
我还可以分享我正在编写的实际代码,上面的示例只是我的想法的一个最小示例。
如果您不需要太多特殊属性功能,则可以对任何变量、属性或属性使用类型提示,如下所示:
class MyClass:
'''Description of my class'''
my_property: float = 5.6
在某些编辑器(包括 VSCode)中,您还可以在变量、属性或属性后面添加文档字符串。
(这始终是有效的 Python,但并非所有编辑器都知道将文档字符串与变量/属性/属性相关联。尝试一下,看看它是否适用于您的编辑器。)
class MyClass:
'''Description of my class'''
my_property: float = 5.6
'''Example description of `my_property`'''
another_property: int = 4
'''And another doc string here'''