如何使用python中的字典比较类型?

时间:2018-12-18 21:29:16

标签: python types

是否可以说类似以下内容:

import pandas as pd


fig_types = ['map', 'chart', 'heading']
fig_objects = [pd.DataFrame, pd.DataFrame, str]
name_to_type = dict(zip(fig_types, fig_objects))

class my_fig_obj:
    def __init__(self, df, fig_type):
        self.df = df
        self.fig_type = fig_type

        if isinstance(df, name_to_type[fig_type]):
            print('yay')


pdf = pd.DataFrame([1,2], [3,4])

x = my_fig_obj('hello', 'heading')
y = my_fig_obj(pdf, 'map')

在pycharm中指出:

“参数化的泛型不能与实例和类检查一起使用”

但是代码似乎可以正常运行。

1 个答案:

答案 0 :(得分:2)

我在PyCharm中已经多次看到这种情况,即使它运行良好,它也会抱怨我的代码不正确,或者我正在做某种编码。我理解为什么即使从技术上讲某些东西也通常被认为是“不好的”编程,但是有时我想知道PyCharm是否只是在曲解某些东西。

我试用了您的代码,当我将字典结构放入Class块时,PyCharm不再将其报告为错误:

class MyFigObj:
    fig_types = ['map', 'chart', 'heading']
    fig_objects = [pd.DataFrame, pd.DataFrame, str]
    name_to_type = dict(zip(fig_types, fig_objects))

    def __init__(self, df, fig_type):
        self.df = df
        self.fig_type = fig_type
        if isinstance(df, name_to_type[fig_type]):
            print('yay')
        print name_to_type

无论出于何种原因,都可以使用直接字符串值的字典。因此,这是我让PyCharm关闭该错误的另一种方法:

name_to_type_str = dict(zip(fig_types, [str(t) for t in fig_objects]))

class MyFigObj:

    def __init__(self, df, fig_type):
        self.df = df
        self.fig_type = fig_type
        if str(type(df)) == name_to_type_str[fig_type]:
            print('yay')
        print name_to_type