2013-10-30 21 views
0

我正在實施字典的重新哈希,所以我有2個哈希表,並且我試圖設置舊的引用新的哈希表。如何更改所有函數的函數內某個對象所指的內容

我有沿的線的東西:

def fart(hashTable): 
    hashTableTwo = mkHashTable(100) 
    hashTable = hashTableTwo 
def main(): 
    hashTableOne = mkHashTable(50) 
    fart(hashTableOne) 
    print(hashTableOne.size) 

mkHashTable(50),使用50作爲它的大小的對象的HashTable。 這打印50,我想它打印100.

我有什麼似乎沒有工作。任何想法如何使其工作?我不允許使用全局變量或對象

回答

0

Python中的賦值(=)是名稱綁定。

所以hashTable = hashTableTwo在放屁函數中不會改變原來的hashTable,它只是將屁函數中的變量名hashTable綁定到hashTableTwo對象。

檢查此篇Is Python call-by-value or call-by-reference? Neither.

解決方法依賴於哈希表的數據結構/對象類型。 dict提供了一些更新其值的方法。

def update_dict(bar): 
    bar = {'This will not':" work"} 


def update_dict2(bar): 
    bar.clear() 
    bar.update(This_will="work") 


foo={'This object is':'mutable'} 

update_dict(foo) 

print foo 

>>> {'This object is': 'mutable'} 


update_dict2(foo) 

print foo 

>>> {'This_will': 'work'}