【发布时间】:2011-04-01 18:21:10
【问题描述】:
我想将一个存储容器位置传递给一个类。有没有比传递字典和密钥更好的方法?传递密钥感觉有点奇怪,尽管它似乎有效。
class GuiWidget():
def __init__(self, storageDict, storageDictKey):
self.storageDict = storageDict
self.storageDictKey = storageDictKey
def inc(self):
self.storageDict[self.storageDictKey] += 1 # in real problem store image
storage = {"k1":0, "k2":0}
w1 = GuiWidget(storage, "k1")
w2 = GuiWidget(storage, "k2")
# calls from gui thread
print storage
w1.inc()
print storage
w2.inc()
print storage
##{'k2': 0, 'k1': 0}
##{'k2': 0, 'k1': 1}
##{'k2': 1, 'k1': 1}
---编辑---
虽然我会更冗长一些,但我喜欢安德烈的方式。它适用于字典或列表。它也给了我这个类解决方案的想法,尽管使用上的差异看起来更美观:
class GuiWidget(object):
def __init__(self, connector):
self.connector = connector
def inc(self):
self.connector.v = (self.connector.v + 1)
class Connector(object):
def __init__(self, container, key):
self.container = container
self.key = key
def get_f(self):
return self.container[self.key]
def set_f(self, z):
self.container[self.key] = z
v = property(fget=get_f, fset=set_f)
storage = {"k1":0, "k2":0}
storageList = [0]
w1 = GuiWidget(Connector(storage, "k1"))
w2 = GuiWidget(Connector(storage, "k2"))
w3 = GuiWidget(Connector(storageList, 0))
# calls from gui thread
print storage
w1.inc()
print storage
w2.inc()
print storage
w3.inc()
print storageList
##{'k2': 0, 'k1': 0}
##{'k2': 0, 'k1': 1}
##{'k2': 1, 'k1': 1}
##[4]
这一切都让我想起了在 C 中传递一个指向结构的指针。
【问题讨论】:
-
现在我意识到,即使在这种情况下,我认为使用类似结构的指针会出现异常,但传递函数确实更好。这样做的原因是它与 MVC 的原则配合得更好。如果您正在使用类似上述结构的连接器/指针,那么您很可能在 Gui/错误的地方做了很多事情。
标签: python dictionary key storage