Calling out a function, not defined error [duplicate]

橙三吉。 提交于 2019-12-25 04:46:15

问题


I'm new to making classes and I'm trying to complete exercise 9-1 in my 'Python Crash Course' book where the last part of the question asks me to call back my method but I end up getting

'not defined error' for describe_restaurant().

Here is my code:

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()

I thought that describe_restaurant shouldn't need to be defined though because I'm calling it out as a function to use?


回答1:


Try:

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()

You need to create a class instance and call it's functions. In addition, as mentioned in the comments, you need to pass self to the instance methods. A short explanation of this can be found here.



来源:https://stackoverflow.com/questions/39602440/calling-out-a-function-not-defined-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!