Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将dict与密钥一起传递以传递存储位置有意义吗?更好的方法?_Python_Dictionary_Key_Storage - Fatal编程技术网

Python 将dict与密钥一起传递以传递存储位置有意义吗?更好的方法?

Python 将dict与密钥一起传递以传递存储位置有意义吗?更好的方法?,python,dictionary,key,storage,Python,Dictionary,Key,Storage,我想将存储容器位置传递给类。有没有比传递口述和钥匙更好的方法?传递钥匙感觉有点奇怪,尽管它似乎有效 class GuiWidget(): def __init__(self, storageDict, storageDictKey): self.storageDict = storageDict self.storageDictKey = storageDictKey def inc(self): self.storageDict[

我想将存储容器位置传递给类。有没有比传递口述和钥匙更好的方法?传递钥匙感觉有点奇怪,尽管它似乎有效

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}
---编辑---

虽然我会更详细一点,但我喜欢安德烈的方式。它与dict或list一起工作。它还为我提供了一个类解决方案的想法,尽管使用上的差异似乎更具装饰性:

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中传递一个指向结构的指针。

我想您希望消除类对存储访问方法的依赖。这就是我的解决方案:

class GuiWidget():
    def __init__(self, accessFunc):
        self.accessFunc = accessFunc
    def inc(self):
        self.accessFunc(self.accessFunc() + 1)

storage = {"k1":0, "k2":0}

def getAccessFunc(key):
    return lambda v = None: v is not None and storage.update({key: v}) or storage[key]

w1 = GuiWidget(getAccessFunc("k1"))
w2 = GuiWidget(getAccessFunc("k2"))


# calls from gui thread
print storage
w1.inc()
print storage
w2.inc()
print storage  

现在我意识到,即使在我认为使用类似指针的结构会出现异常的情况下,传递函数确实更好。这样做的原因是,它与MVC的原则配合得更好。如果您使用的是上述连接器/指针式结构,那么很可能您在Gui/错误的地方做了很多事情。