2011-12-23 63 views
1

我試圖在Python中創建類的實例時返回字典的值,但我一直收到「無」返回。嘗試在Python中返回字典的值時發出「無」

我對Python很陌生,所以我確信這個答案很簡單。

運行以下後:

class TestTwo(object): 

    def __init__(self): 
      self.attributes = { 
      'age': "", 
      'name' : "", 
      'location': "" 
    } 

    def your_age(self): 
     self.attributes['age'] = raw_input("What is your age? > ") 
     self.your_name() 

    def your_name(self): 
     self.attributes['name'] = raw_input("What is your name? > ") 
     self.your_location() 

    def your_location(self): 
     self.attributes['location'] = raw_input("Where do you live? > ") 
     self.results() 

    def results(self): 
     print "You live in %s" % self.attributes['location'] 
     print "Your number is %s" % self.attributes['age'] 
     print "Your name is %s" % self.attributes['name'] 
     d = self.attributes 
     return d 

output = TestTwo().your_age() 
print output 

我結束了這一點:

MacBook-Pro-2:python johnrougeux$ python class_test.py 
What is your age? > 30 
What is your name? > John 
Where do you live? > KY 
You live in KY 
Your number is 30 
Your name is John 
None 

而是 「無」,我所期待的「{ '年齡' 的: '30',「名':'John','location':'KY'}「

我錯過了什麼?

+1

這是一個完全倒退的方法來使用類。獲取構造對象所需的信息,然後構造它。類不應該負責獲取該信息,而只是爲了使用它。 – 2011-12-23 06:31:56

回答

6

只有results()返回一些東西。您需要在其他功能返回,如果你想讓他們返回的東西傳遞沿調用鏈它的返回值,也:

def your_age(self): 
    self.attributes['age'] = raw_input("What is your age? > ") 
    return self.your_name() 

def your_name(self): 
    self.attributes['name'] = raw_input("What is your name? > ") 
    return self.your_location() 

def your_location(self): 
    self.attributes['location'] = raw_input("Where do you live? > ") 
    return self.results() 

當然這種鏈接是極其醜陋的;但我相信你已經知道了。如果沒有,重寫你的代碼,如下所示:

在這些函數中,只需設置值並執行而不是調用其他函數之一。然後添加功能,諸如這樣的:使用類

def prompt_data(self): 
    self.your_age() 
    self.your_name() 
    self.your_location() 

在代碼中,這樣做:

t2 = TestTwo() 
t2.prompt_data() 
output = t2.results() 
+0

謝謝,這真的很有幫助。正是我在找什麼! – 2011-12-23 02:44:08

0

功能your_age()不返回任何值,當然輸出是無

相關問題