2014-01-17 24 views
0

作爲Python的新手,但仍然無法逃避,我一直在困擾這個問題。我想要做的是傳遞一個字符串到函數中來獲得它extend ed。如何在Python中傳遞字符串到函數

以下是我有:

def replace(source, destination): 
    local_source = src_tree.find("source") 
    local_destination = dest_tree.find("destination") 
    local_destination.extend(local_source) 

replace(source=".//animal-list/dog", destination=".//animal-list/dog") 

,如果我不把它放在一個函數這段代碼將工作。但是因爲我有數百個這樣的「expend」,我不得不實現,所以爲什麼不是好的函數調用。

本來我都這樣了,它的工作原理是什麼,我需要:

src = src_tree.find('.//animal-list/dog') 
dest = dest_tree.find('.//animal-list/dog') 
dest.extend(src) 

什麼,會做與src狗「替換」的dest狗。完美的作品,但我試圖把它變成一個更容易使用的功能。

我的問題是,我在做什麼錯誤的功能?因爲它正在拋出異常。

Traceback (most recent call last): 
    File "test.py", line 28, in <module> 
    replace(source=".//animal-list/dog", destination=".//animal-list/dog") 
    File "test.py", line 13, in replace 
    local_destination.extend(local_source) 
AttributeError: 'NoneType' object has no attribute 'extend' 
+2

'「源」'和'「目的地」'不應該用引號括起來。 – Ryan

+0

奇怪的我以爲我嘗試過,但仍然給我例外。我可能是錯的,現在已經在這個程序(不是特別是這個問題)上工作了12個多小時。 (衝週三發佈)。問題是,我星期三之前不會說Python。 – misterbear

+0

@tyler你確定它是_same_異常嗎? – aIKid

回答

2

你引用的東西,應該是變量(sourcedestination)。 它應該是:

def replace(source, destination): 
    local_source = src_tree.find(source) 
    local_destination = dest_tree.find(destination) 
    local_destination.extend(local_source) 
1

這裏要傳遞一個字符串,而不是變量

local_destination = dest_tree.find("destination") 

也許dest_tree.find正在恢復,因爲這些根本。如果你想通過自己的價值觀試試這個

local_destination = dest_tree.find(destination) 

而且同樣,你必須使用的"source"代替source

相關問題