使用 python 中的循环从列表创建变量名称

create variable name from list using a loop in python

我正在尝试从一个列表中生成一堆变量,这些变量将被另一个函数调用。

如果我单独创建它们(如代码的注释部分),一切正常(好的,我的意思是,我可以使用下面列出的 get_data 函数访问日期)。但是,当我使用循环时,get_data 给出错误:

File "main.py", line 97, in get_data
    dAu = self.Author.get_text()
AttributeError: 'MyWindow' object has no attribute 'Author'

所以,很明显,在循环内部,EDIT我期待,for field[0],

self.field = self.field[0]=self.Author

但事实并非如此。编辑完成

self.field != self.Author

如我所愿。 我怎样才能得到它?

有问题的代码是:

    #  Generate the Entry fields
    self.notebook = Gtk.Notebook()
    # self.LAuthor = Gtk.Label("Author")
    # self.EAuthor = Gtk.Entry()
    # self.page = Gtk.Grid()
    # self.page.attach(self.LAuthor, 0, 0, 2, 1)
    # self.page.attach_next_to(self.EAuthor, self.LAuthor, Gtk.PositionType.RIGHT, 1, 1)
    # self.notebook.append_page(self.page, Gtk.Label("Trial"))

    xpos = 0
    minf = 0
    fields = ["Author",  "Year",  "Journal", "Title", "Publisher", "Page",
              "Address", "Annote", " Booktitle", "Chapter", "Crossred",
              "Edition", "Editor", "HowPublished", "Institution", "Month",
              "Note", "Number", "Organization", "Pages", "Publishers",
              "School", "Series", "Type"]
    Tabs = ["Essential", "Publishers", "Extra I", "Extra II"]
    for note in range(int(len(fields)/6)):
        ypos = 0
        self.npage = "page"+str(note)
        self.npage = Gtk.Grid()
        self.npage.set_border_width(10)
        maxf = minf+6
        for field in fields[minf:maxf]:
            print(field)
            self.lfield = "L" + field
            self.lfield = Gtk.Label(field)
            self.field = Gtk.Entry()
            self.field.set_placeholder_text(field)
            self.npage.attach(self.lfield, xpos, ypos, 2, 1)
            self.npage.attach_next_to(self.field, self.lfield,
                                      Gtk.PositionType.RIGHT, 1, 1)
            ypos += 1

        self.notebook.append_page(self.npage, Gtk.Label(Tabs[note]))
        minf = maxf

get_data 函数只是:

def get_data(self, widget):
    dAu = self.Author.get_text()
    print(dAu)

请帮忙。

使用字典 - 例如:

self.all_fields = dict()

field = "Author"
self.all_fields[field] = ...
# self.all_fields["Author"] = ...

然后你可以使用

def get_data(self, widget):
    dAu = self.all_fields["Author"].get_text()
    print(dAu)