2016-08-19 147 views
-3

目前通過Python的速成班工作,這個例子是給我找麻煩NameError:名「name」沒有定義

class Restaurant(): 
    def __init__(self, restaurant_name, cuisine_type): 
     """ initializing name and cuisine attributes""" 
     self.restaurant_name = name 
     self.cuisine_type = c_type 

    def greeting(self): 
     """simulate greetting with restaurant info...""" 
     print(self.name.title() + " is a " + self.c_type.title() 
     + " type of restaurant.") 

    def open_or_nah(self): 
     """ wheteher or not the restaurant is open in this case they will be always""" 
     print(self.name.title() + " is open af") 


    china_king = Restaurant('china king', 'chinese') 
    china_king.greeting 
    china_king.open_or_nah 

控制檯一直給我

Traceback (most recent call last): 
    File "python", line 16, in <module> 
    File "python", line 4, in __init__ 
NameError: name 'name' is not defined 

我搜索錯誤爲什麼造成這個原因,但我無法弄清楚。怎麼了?

+2

你的參數被稱爲'restaurant_name' –

回答

2

看起來像一個小失誤,只需要修改它在你__init__

self.name = restaurant_name 
+1

另外也可以,因爲他們使用'name','self.name = restaurant_name' – Li357

+0

和'self.c_type = cuisine_type'爲好。 – acw1668

+0

是的,真的可能有更多的錯誤在程序 – AlokThakur

0
class Restaurant(): 
    def __init__(self, restaurant_name, cuisine_type): 
     """ initializing name and cuisine attributes""" 
     self.restaurant_name = restaurant_name 
     self.cuisine_type = cuisine_type 

名不是你的類初始化的一部分。它應該是restaurant_name,這是你作爲初始化的一部分接收到的。

或將其更改爲以下

def __init__(self, name, c_type): 
1

你的問題是你__init__方法在Restaurant類。

class Restaurant(): 
    def __init__(self, restaurant_name, cuisine_type): 
     """ initializing name and cuisine attributes""" 
     self.restaurant_name = name 
     self.cuisine_type = c_type 

在這裏,你可以看到,每次創建類類型Restaurant的新實例,你必須在兩個參數傳遞的參數,restaurant_namecuisine_type

__init__函數只能看到傳入它的東西,所以當你告訴它尋找name它變得「困惑」。

__init__方法想:「name什麼是name我只知道restaurant_namecuisine_type,所以我不得不拋出一個錯誤?」。

您的代碼應該是這樣的:

class Restaurant(): 
def __init__(self, restaurant_name, cuisine_type): 
    """ initializing name and cuisine attributes""" 
    self.restaurant_name = restaurant_name 
    self.cuisine_type = cuisine_type 
1

只是一個小失誤,從混合變量名。更改__init__功能

def __init__(self, name, cuisine_type): 
    """ initializing name and cuisine attributes""" 
    self.name = name 
    self.cuisine_type = c_type 
相關問題