2016-08-19 98 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 
相关问题