1

我有一个函数可以重复索引到具有相同键的字典中。是否可以参考相关项目?

def my_function(self, event):
    self.__observers[event] ... #this is get is performed multiple times
    observer_ref = self.__observers[event] #can I make this a reference to the value?

更新: 目标是不复制 self.__observers[event] 中的内容。我正在寻找类似于 C++ 的行为,例如

int x = 1
int& y = x #reference to y, not a copy
4

3 回答 3

3

当您在 Python 中为名称(变量)赋值时,变量只是对该值的引用。

因此,例如说self.__observers[event]以空列表开头,以下代码可以正常工作:

assert self.__observers[event] == []
observer_ref = self.__observers[event]
observer_ref.append(1)                    # this modifies self.__observers[event]
assert self.__observers[event] == [1]

但是,正如 BrenBarn 所指出的,如果您要分配observer_ref一个新值,它根本不会修改self.__observers[event]

于 2012-06-15T19:42:45.433 回答
0

这实际上取决于您所说的“参考”是什么意思。...而且它还取决于您将如何处理参考。例如。

class Test(object):
    def __init__(self):
        self.__observers = {'event1': {'test':'this'}, 'event2': {'test':'that'}}

    def get_observers(self):
        return self.__observers

    def my_function(self, event):
        observer_ref = self.__observers[event]
        return observer_ref

if __name__ == '__main__':
    t = Test()

    my_event = 'event1'  

    print('From class: {}'.format(t.get_observers()[my_event]))
    my_ref = t.my_function(my_event)
    print('From my_function: {}'.format(my_ref))

    my_ref['something'] = 'else'

    print('From my_function after addition: {}'.format(my_ref))
    print('From class after addition: {}'.format(t.get_observers()[my_event]))

    my_ref = 'something else entirely'

    print('From my_function after re-assignment: {}'.format(my_ref))
    print('From class after re-assignment: {}'.format(t.get_observers()[my_event]))

结果是 :

From class: {'test': 'this'}
From my_function: {'test': 'this'}
From my_function after addition: {'test': 'this', 'something': 'else'}
From class after addition: {'test': 'this', 'something': 'else'}
From my_function after re-assignment: something else entirely
From class after re-assignment: {'test': 'this', 'something': 'else'}

基本上,如果您reference是某种对象,您可以使用该引用来操作该对象。您只是不能将引用的名称重新分配给其他东西,并将其反映在您从中提取引用的原始对象中。

于 2012-06-15T19:43:08.450 回答
0

当然。你为什么不试试看呢?

但是,正如评论中指出的那样,这取决于您所说的“参考”是什么意思如果您按照您的建议进行操作,分配给您的新变量不会改变字典。

>>> d = {'a': 1}
>>> d['a']
1
>>> x = d['a']
>>> x
1
>>> x = 2
>>> d
{u'a': 1}
于 2012-06-15T19:29:56.310 回答