繁体   English   中英

自定义 class 属性的类型提示

[英]Type hint for custom class atributes

我对在 python 中使用类型提示很陌生。 我在 package 中有一个包含多个模块的应用程序以及与它们关联的类。 我一直在尝试找到一些类型提示解释,说明当有多个脚本并且定义的类型来自 object 脚本加载到另一个模块中时,它是如何工作的。 这是一个非常简化的版本,用于解决类型提示使用上的这种混淆。

鉴于主应用程序有一个脚本,如下所示:

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'])

package 模块包含两个模块:

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

plot_figure方法中styler参数的类型提示应该是什么? 本质上它是一本字典。 显然它不应该是任何字典,而是作为FigureFormatting class 实例的属性的字典。 是否应该将该模块也导入Plotter模块,以便可以引用 class 名称?

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作为基础 class,文档建议这是预期用途。 (被调用的版本似乎存在以支持 Python 3.6 之前的版本,这些版本不允许变量注释。请注意, TypedDict在被提升为typing之前处于实验性typing_extensions中。)

class StylerProperties(TypedDict):
    prop1: int
    prop2: int


class Styler(TypedDict):
    light: StylerProperties
    dark: StylerProperties

进一步要求 dict 来自特定的 class 属性没有多大意义,因为由属性引用不会更改dict值。 如果作为FigureFormatter的一个属性很重要,那么只需要一个FigureFormatter的实例并自己提取dict

def plot_figure(self, f: FigureFormatter):
    styler = f.styler
    ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM