首页 > 解决方案 > 包含类的动态填充字典的自动完成?

问题描述

我有一个 GUI,通过它我加载了一些数据。加载文件时,其文件名用作标识符,填充 GUI 和下面的字典,以跟踪每个文件的当前状态。

但是,使用这种方法,我无法从MetaData课堂上获得任何自动完成功能,例如当我想访问data.container.[GUIcurrentFile].one_of_many_attributes.

有没有解决的办法?也许以完全不同的方式将文件保存在内存中?人们在这种情况下通常会做什么?我对GUI开发不太熟悉。

class Data:
    def __init__(self):
        self.container = dict()

    def load(self, name):
        self.container[name] = MetaData()

class MetaData:
    def __init__(self):
        self.one_of_many_attributes = None


# This is instantiated in the main part of the GUI, e.g. self.data = Data()
data = Data()


## Series of events happening through the GUI
# Grab loaded file through a GUI
GUIcurrentFile = "file1"
data.load(GUIcurrentFile)

GUIcurrentFile = "file2"
data.load(GUIcurrentFile)

# Each file has separate attributes
data.container[GUIcurrentFile].one_of_many_attributes = "foo"

# File is removed from GUI, and can easily be removed from dictionary internally
data.container.pop(GUIcurrentFile)

标签: pythonoopdictionaryautocomplete

解决方案


好的,所以类型提示终于为我点击了。我希望原始标题与此答案有关。否则,请随时编辑它。

首先定义 MetaData,如果实现方法以返回“MetaData”类型的对象,则为 PyCharm 添加类型提示非常简单。

class MetaData:
    def __init__(self):
        self.foo = None
        self.really_long_name = None

class Data:
    def __init__(self):
        self.container = dict()

    def load(self, name):
        self.container[name] = MetaData()

    def get(self, name) -> MetaData: # specify what dict lookup returns
        return self.container[name]

data = Data()
data.load("file1")
data.get("file1").foo

在此处输入图像描述


推荐阅读