如何解决自定义类属性的类型提示
我对在 python 中使用类型提示很陌生。我有一个应用程序,其中包含一个包中的多个模块以及与它们关联的类。我一直试图找到一些类型提示解释,当有多个脚本时它是如何工作的,并且定义的类型来自一个对象,该对象的脚本加载到另一个模块中。 这里有一个非常简化的版本,用于解决类型提示使用上的混淆。
鉴于有这样一个主应用程序的脚本:
from modules.FigureFormatter import FigureFormatter
from modules.Plotter import Plotter
class MainApp:
def __init__(self):
formatter = FigureFormatter()
plotter = Plotter()
plotter.plot_figure(formatter.styler['light'])
modules 包包含两个模块:
class FigureFormatter:
def __init__(self):
self.styler = {'light': {'prop1': 1,'prop2': 2},'dark': {'prop1': 1,'prop2': 2}}
和
from typing import Dict
class Plotter:
def __inti__(self):
# Some initialization stuff
pass
def plot_figure(self,styler: Dict):
# Plotting figure
pass
styler
方法中 plot_figure
参数的类型提示应该是什么?本质上它是一本字典。显然它不应该是任何字典,而是作为 FigureFormatting
类实例的属性的字典。是否应该将该模块也导入到 Plotter
模块中,以便可以引用类名?
解决方法
Python 3.8 引入了 TypedDict
提示,它可以指定一个字典,其中包含映射到特定类型的特定 str
值键。例如:
# In modules.FigureFormatter
from typing import TypedDict
StylerProperties = TypedDict('StylerProperties',prop1=int,prop2=int)
StylerType = TypedDict('Styler',light=StylerProperties,dark=StylerProperties)
# In modules.Plotter
from modules.Formatter import StylerType
class Plotter:
...
def plot_figure(self,styler: StylerType):
...
您也可以将它 TypedDict
用作基类,文档建议这是预期用途。 (被调用的版本似乎支持 Python 3.6 之前的版本,该版本不允许变量注释。请注意,TypedDict
在提升为 typing_extensions
之前处于实验性 typing
中。 )
class StylerProperties(TypedDict):
prop1: int
prop2: int
class Styler(TypedDict):
light: StylerProperties
dark: StylerProperties
进一步要求 dict 来自特定的类属性没有多大意义,因为被属性引用不会改变 dict
值。如果 FigureFormatter
的属性很重要,那么只需要一个 FigureFormatter
的实例并自己提取 dict
:
def plot_figure(self,f: FigureFormatter):
styler = f.styler
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。