调出函数,未定义错误
问题描述:
我是上课的新手,我正在尝试完成 Python速成课程这本书中的练习9-1,问题的最后一部分要求我回叫我的方法,但最终还是得到了
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
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
应该
答
尝试:
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
传递给实例方法。对此的简短说明可以在此处。
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.