2016-09-20 78 views
0

我是新來的類,我想在我的「Python速成課程」書中完成練習9-1,問題的最後部分要求我回電我的方法,但我最終得到調用一個函數,沒有定義的錯誤

'未定義的錯誤'爲describe_restaurant()

這裏是我的代碼:

class Restaurant(): 
    def __init__(self, r_name, c_type): 
     self.r_name = r_name 
     self.c_type = c_type 

    def describe_restaurant(): 
     print(self.r_name.title()) 
     print(self.c_type.title()) 

    def open_restaurant(): 
     print(self.r_name + " is now open!") 

Restaurant = Restaurant('Joe\'s Sushi', 'sushi') 

print(Restaurant.r_name) 
print(Restaurant.c_type) 

describe_restaurant() 
open_restaurant() 

我認爲describe_restaurant應該不需要,因爲我呼喚它作爲使用功能雖然被定義?

+0

您應該首先創建'Restaraunt'對象,然後從新創建的對象調用'describe_restaurant' –

+0

這是一個類函數。您需要使用類對象調用類函數。 – MooingRawr

+3

你應該重新審視類的課程計劃。下面是通過官方教程的另一種看法:https://docs.python.org/3/tutorial/classes.html – idjaw

回答

2

嘗試:

class Restaurant(): 
    def __init__(self, r_name, c_type): 
     self.r_name = r_name 
     self.c_type = c_type 

    def describe_restaurant(self): 
     print(self.r_name) 
     print(self.c_type) 

    def open_restaurant(self): 
     return "{} is now open!".format(self.r_name) 

restaurant = Restaurant('Joe\'s Sushi', 'sushi') 

print(restaurant.r_name) 
print(restaurant.c_type) 

restaurant.describe_restaurant() 
restaurant.open_restaurant() 

您需要創建一個類的實例,並調用它的功能。另外,如評論中所述,您需要將self傳遞給實例方法。這個簡短的解釋可以在here找到。

+0

你是對的。修正了我的代碼片段。沒有看到... – albert

+0

修正了這個問題。對不起,對我自己有點困惑:) – albert

+0

對於最近的回覆,我很抱歉,我最近沒有太多時間編寫代碼。我會看看你的鏈接,希望它能幫助我更好地理解函數和類。 :) – PhantomDiclonius

相關問題