I would like to pass a storage container location to a class. Is there a better way to do it than by passing a dict and the key? Passing keys feels a little odd, though it seems to work.
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}
—edit—
Though I would do it a little more verbosely, I like Andrey’s way. It works with either dict or list. It also gave me the idea for this solution with a class, though the differences in use seem more cosmetical:
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]
All this reminds me of passing a pointer to a struct in C.
I guess you want to eliminate the dependence of your class on storage access method. That’s my solution: