2013-11-14 54 views
0

我無法再繼續使用我正在學習的課程並且有問題。我會先發布我的代碼。我如何獲得課堂上的意見和主要腳本

我的類代碼如下所示:

import requests 
import json 

class requestNew: 

    def __init__(self): 
     self.countrychoice = [] 
     self.citychoice = [] 

    def countryChoice(self): 
     countryc = input("Enter which country your city is in(in english): ") 
     self.countrychoice.append(countryc) 

    def cityChoice(self): 
     cityc = input("Enter the name of the city: ") 
     self.citychoice.append(cityc) 

,你可以看到我輸入def countryChoice(self):def cityChoice(self): 我想出來的類函數,進入主腳本。

這是我的主要腳本中的相關部分看起來像此刻:

from requestnew import requestNew 


if __name__ == '__main__': 
    """Introducion""" 
    print ("\nThis program lets you see a weather forecast for your choosen city.") 
    rq = requestNew() 


    while True: 
     print("\nWhen you have typed in country and city, press 3 in the menu to see the weather forecast for your choice.\n") 
     menu = input("\nPress 1 for country\nPress 2 for city\nPress 3 to see forecast\nPress 4 to exit\n") 
     if menu == "1": 
      rq.countryChoice() 
     elif menu == "2": 
      rq.cityChoice() 

這時我mainscript只是調用類函數,他們做的輸入工作。但是,我如何從課堂上獲得輸入並輸入主文稿。

正如你可以在我的課看到輸入追加到一個列表:

def countryChoice(self): 
    countryc = input("Enter which country your city is in(in english): ") 
    self.countrychoice.append(countryc) #Here 

如果我得到了我的主腳本的輸入,它甚至有可能仍然獲得輸入要追加到我班上的self.countrychoice.append(countryc)?我需要能夠因爲後來在我的課我使用列表項這樣做:

def forecastRequest(self): 
    r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + self.countrychoice[-1] + "/" + self.citychoice[-1] + ".json") 
    self.data = r.json() 

正如你可以在代碼中看到上面我使用的列表項self.countrychoice[-1] + "/" + self.citychoice[-1],這是爲我的API獲得正確的地址。

所以我的問題是,我怎樣才能得到輸入的課堂和我的主要腳本沒有搞亂附加到列表?如果這甚至是可能的。

對不起,如果有什麼不好解釋或書面。自從我是一名初學者以來,這對我來說確實令人困惑。

回答

1

要從外部訪問對象的屬性,除了使用對象變量而不是self之外,您可以從內部執行相同的操作。

例如,類裏面,你這樣做:

self.countrychoice[-1] + "/" + self.citychoice[-1] 

類外,與存儲在rq的情況下,你這樣做:

rq.countrychoice[-1] + "/" + rq.citychoice[-1] 

同樣,你打電話後rq.forecastRequest(),您可以訪問數據爲rq.data。所以,你可以這樣寫:

while True: 
    print("\nWhen you have typed in country and city, press 3 in the menu to see the weather forecast for your choice.\n") 
    menu = input("\nPress 1 for country\nPress 2 for city\nPress 3 to see forecast\nPress 4 to exit\n") 
    if menu == "1": 
     rq.countryChoice() 
    elif menu == "2": 
     rq.cityChoice() 
    elif menu == "3": 
     rq.forecastChoice() 
     for line in rq.data.splitlines(): 
      print(line) 
2

你需要從方法返回一個值:

def countryChoice(self): 
    countryc = input("Enter which country your city is in(in english): ") 
    self.countrychoice.append(countryc) 
    return countryc 

在主腳本,那麼你可以得到國家的選擇:

countryChoice = rq.countryChoice() 

此外,您還可以從所有的值通過訪問rq.countrychoice列出。同樣的推理適用於cityChoicerq.citychoice