gpt4 book ai didi

python - 如何对以编程方式设置的属性调用方法?

转载 作者:行者123 更新时间:2023-12-01 02:02:00 26 4
gpt4 key购买 nike

这是 How do you programmatically set an attribute? 的后续问题.

我了解了如何使用 setattr(x, attr, value) 设置属性值。

我如何调用 attr 上的方法?

举个例子,我想创建并设置与字典相对应的 Tkinter Entry 对象的值,其中键是属性,值是要分配给属性的值。

我的蛮力方法有效:

from tkinter import Tk, Button, filedialog, Label, Frame, BOTH, Entry, END, StringVar


class Example(Frame):
def __init__(self, master=None):
"""Initialize UI and set default values."""
# https://stackoverflow.com/questions/285061/how-do-you-programmatically-set-an-attribute.

Frame.__init__(self, master)
self.master = master

myDict = {'a': 'String A', 'b': 'String B', 'c': 'String C'}

self.a = StringVar()
self.a.set(myDict['a'])
self.aEntry = Entry(self, textvariable=self.a)
self.aEntry.grid(row=0, column=1)

self.b = StringVar()
self.b.set(myDict['b'])
self.bEntry = Entry(self, textvariable=self.b)
self.bEntry.grid(row=1, column=1)

self.c = StringVar()
self.c.set(myDict['c'])
self.cEntry = Entry(self, textvariable=self.c)
self.cEntry.grid(row=2, column=1)

self.pack(fill=BOTH, expand=1)

root = Tk()
app = Example(root)
root.mainloop()

循环方法看起来像这样:

from tkinter import Tk, Button, filedialog, Label, Frame, BOTH, Entry, END, StringVar


class Example(Frame):
def __init__(self, master=None):
"""Initialize UI and set default values."""
# https://stackoverflow.com/questions/285061/how-do-you-programmatically-set-an-attribute.
Frame.__init__(self, master)
self.master = master

myDict = {'a': 'String A', 'b': 'String B', 'c': 'String C'}

rowCount = 0
for key, value in myDict.items():
setattr(self, key, StringVar()) # Works

# self.a.set('String A')
self.key.set(value) # Does not work

# self.aEntry = Entry(self, textvariable=self.a)
setattr(self, key + 'Entry', Entry(self, textvariable=???)) # Does not work

# self.aEntry.grid(row=0, column=1)
self.key + 'Entry'.grid(row=rowCount, column=1) # Does not work
rowCount += 1

self.pack(fill=BOTH, expand=1)


root = Tk()
app = Example(root)
root.mainloop()

如何重写标有“# 不起作用”的行以使循环起作用?

这不仅仅是一个 Tkinter 问题。我可以想到其他情况,人们可能想要调用属性上的方法,该方法的名称被分配给字符串变量。我将不胜感激指导。

最佳答案

我不会为此使用单独的属性;我将使用关联的 EntryStringVar 对象对的 dict

getattrsetattr各有其用处,但不能取代dict的合理使用。

class Example(Frame):
def __init__(self, master=None):
"""Initialize UI and set default values."""
# https://stackoverflow.com/questions/285061/how-do-you-programmatically-set-an-attribute.
Frame.__init__(self, master)
self.master = master

myDict = {'a': 'String A', 'b': 'String B', 'c': 'String C'}

self.entries = {}

for rowCount, (key, value) in enumerate(myDict.items()):
sv = StringVar()
sv.set(value)

e = Entry(self, textvariable=sv)
e.grid(row=rowCount, column=1)

self.entries[key] = (e, sv)

self.pack(fill=BOTH, expand=1)

关于python - 如何对以编程方式设置的属性调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49518479/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com