Python Forum

Full Version: not defined error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
class Restaurant():
    """Restaurant example"""
    
    def __init__(self, restaurant_name, cuisine_type):
        """Initialize restaurant name and cuisine type attributes"""
        self.name = restaurant_name
        self.type = cuisine_type
        
    def describe_restaurant(self):
	    """Tells the name and type of restaurant"""
	    print(self.name.title() + " has" + self.type.title() + " food.")
        
    def open_restaurant(self):
        """Tells that the restaurant is open"""
        print(self.name.title() + " is now open!")
        
print(describe_restaurant('saltgrass', 'steak'))
        
print(open_restaurant('saltgrass'))
traceback (most recent call last):
File "Restaurant", line 17, in <module>
print(describe_restaurant('saltgrass', 'steak'))
NameError: name 'describe_restaurant' is not defined
That is not how OOP works. describe_restaurant is method of class Restaurant. You need to create an instance of the class then call the method
class Restaurant():
    """Restaurant example"""
     
    def __init__(self, restaurant_name, cuisine_type):
        """Initialize restaurant name and cuisine type attributes"""
        self.name = restaurant_name
        self.type = cuisine_type
         
    def describe_restaurant(self):
        """Tells the name and type of restaurant"""
        print(self.name.title() + " has " + self.type.title() + " food.")
         
    def open_restaurant(self):
        """Tells that the restaurant is open"""
        print(self.name.title() + " is now open!")

restaurant = Restaurant('saltgrass', 'steak')
another_restaurant = Restaurant('Great Dracon', 'chinese')

restaurant.describe_restaurant()
another_restaurant.describe_restaurant()
restaurant.open_restaurant()
another_restaurant.open_restaurant()
Output:
Saltgrass has Steak food. Great Dracon has Chinese food. Saltgrass is now open! Great Dracon is now open!
Awesome thanks much!