2011-06-21 193 views
0

下面是檢查網站價格並將其發送到Twitter的代碼。正如你所看到的,在第22行中,我將第一個函數(取得價格)作爲第二個函數中的參數傳遞給Twitter。當我運行這個時,我不斷收到一個錯誤消息,說「TypeError:send_to_twitter()不接受任何參數(給出1)」。無法弄清楚爲什麼它不會引發爭論。任何想法?函數不會帶參數

import urllib.request 
import time 

def get_price(): 
    page = urllib.request.urlopen("http://www.beans-r-us.biz/prices.html")#get price from website 
    text = page.read().decode("utf8") 
    where = text.find('>$') 
    start_of_price = where + 2 
    end_of_price = start_of_price + 4 
    return float(text[start_of_price:end_of_price]) 


def send_to_twitter(): 
    password_manager = urllib.request.HTTPPasswordMgr() 
    password_manager.add_password('Twitter API','http://twitter.com/statuses','eyemademusic','selfishgene') 
    http_handler = urllib.request.HTTPBasicAuthHandler(password_manager) 
    page_opener = urllib.request.build_opener(http_handler) 
    urllib.request.install_opener(page_opener) 
    params = urllib.parse.urlencode({'status':msg}) 
    resp = urllib.request.urlopen('http://twitter.com/statuses/update.json', params) 
    resp.read 

price_now = input('Would you like to check the price? Y/N') 
if price_now == 'Y': 
    send_to_twitter(get_price()) 
else: 
    price = 99.99 
    while price > 4.74: 
     time.sleep(900) 
     price = get_price 
    send_to_twitter('Buy!') 

回答

5
def send_to_twitter(name_of_the_argument_you_want): 
3

def send_to_twitter():應該def send_to_twitter(msg):

resp.readresp.read()price = get_priceprice = get_price()

3

正因爲如此:

def send_to_twitter(): 
    ... 

定義一個零參數的函數。想一想這一秒;你會如何引用你想要的觀點?這個函數裏面有什麼名字?在函數名稱後面的圓括號內,您需要列出函數採用的所有參數的名稱。

而且,當你有這樣的:

send_to_twitter(get_price()) 

您實際上並不傳遞函數get_price作爲參數傳遞給send_to_twitter,你調用get_price和傳球的結果。如果要傳遞函數,則只需使用函數名稱,而不是括號,如下所示:

send_to_twitter(get_price)