我搜索了論壇,但我無法準確找到我正在尋找的內容。我有這段代碼,我在一個類中有很多屬性(超過 300 行),因為它是一個包含很多東西的 gui。因此,我使用 exec 制作了一個可以動態設定屬性的函式。
MyClass():
#some code
def set_attributes(self,name,chain_index):
exec(f'self.{name}chk.set(self.chaines01[0][{chain_index}])')
exec(f'self.{name}dateEntry.delete(0, "end")')
exec(f'self.{name}dateEntry.insert(0, self.listdates[{chain_index}])')
exec(f'self.{name}commentEntry.delete(0, "end")')
exec(f'self.{name}commentEntry.insert(0, self.listcomments[{chain_index}])')
self.set_attributes('attribute1',1)
self.set_attributes('attribute2',1)
...
但是,我不確定這是一種非常 Pythonic 的方式,我不太了解 exec 的注意事項,我不確定屬性是否在“self”中正確實體化。
我在這里看到https://lucumr.pocoo.org/2011/2/1/exec-in-python/我可以在字典中執行 exec :
>>> code = compile('a = 1 2', '<string>', 'exec')
>>> ns = {}
>>> exec code in ns
>>> print ns['a']
3
但我想用 tkinter 功能實作類實體屬性......
我還在另一篇文章中看到他們使用 types.MethodType。我應該使用 types.MethodType(self.{name}chk.set(self.chaines01[0][{chain_index}]), self) 嗎?def_attributes 函式中的每個屬性?還是 types.DynamicClassAttribute?
在不使用 exec 的情況下,我如何將 exec 替換為與 exec 相同的 Python 函式?
uj5u.com熱心網友回復:
查看types.MethodType 是如何使用的?似乎我無法使用 types.MethodType 將屬性分配給類實體,因為它需要一個可呼叫的。
查看什么是 DynamicClassAttribute 以及如何使用它?似乎 DynamicClassAttribute 用于元類屬性問題,并且對于將屬性接地到“自我”沒有任何用處。
我用 self.attribute= 和 setattr(self,attribute,value) 在 testClass 中嘗試了 exec,并且屬性設定正確。
但是我讀過 exec 永遠不應該在呼叫代碼的命名空間中使用。
我終于找到了一種避免 exec 與本地命名空間沖突的好方法:
exec(compile(f'self.{name}chk.set(self.chaines01[0][{chain_index}])', '<string>', 'exec')) in self.__dict__
它作業正常
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/452236.html
