2017-05-06 120 views
0

爲什麼我不能得到結果(肯德基是美國餐館)?我如何改變它?我是否符合要求?沒有得到期望的結果 - Python

class Restaurant: 
    __name="" 
    __cuisine="" 


    def __init__(self,name,cuisine): 
     self.__name=name 
     self.__cuisine=cuisine 

    def describe_restaurant(self): 
      print(self.__name, " is a ",self.__cuisine ," restarurant.") 

    def open_restaurant(self): 
      print(self.__name ," is open.") 


def test(): 
    p=Restaurant("KFC","American") 
    print(p.describe_restaurant) 
+0

這是因爲'p'在't'定義,因此它超出了範圍。你可以將它作爲參數傳遞('h(p)') –

+0

@ t.m.adam已經完美回答了。如果我可以補充一點,另一個迴應建議的全局變量在任何編程語言中通常都不被認爲是最佳實踐。此外,根據您的代碼要求,看起來您根本不需要有兩個單獨的函數。單一功能「測試」應該充分滿足附件中提到的要求。此外,打印p.describe_restaurant返回值的調用將失敗,因爲describe_restaurant()沒有返回值。僅僅打電話給p.describe_restaurant()。 – YashTD

+0

我不會在'describe_restaurant' en'open_restaurant'中使用print語句,讓它返回一個字符串。 – Elmex80s

回答

1

describe_restaurant是一個函數。當你寫

print(p.describe_restaurant) 

你會得到一個函數的字符串表示。然而,你想調用這個函數,讓它執行,並打印它的返回值。要做到這一點,通過添加括號稱之爲:

p.describe_restaurant() 

此外,一定要實際調用您的test方法,像這樣:

test() 
+0

謝謝你,我修改它,但它仍然無法正常工作。 –

+0

@TianxuZang對我來說很好,還有[ideone](http://ideone.com/Rkq6Pj)。你能否確認你有與[ideone上發佈的相同的代碼](http://ideone.com/Rkq6Pj)? – phihag

+0

謝謝,它的作品! –