2013-11-14 52 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