Python 创建实例例题9-1 《python 从入门到实践》
里面传参,函数定义明明是两个参数,但是我传两个会报错,我又传了一个,结果输出结果不对。
class restaurant:
def __init__(self,restaurant_name,cuisine_type):
self.name = restaurant_name
self.type = cuisine_type
def describe_restaurant(self,restaurant_name,cuisine_type): #必须传递2个参数
print(f"The {restaurant_name} is {cuisine_type}")
def open_restaurant(self,restaurant_name): #必须传递1个参数
print(f"The {restaurant_name} is opening>>>")
c = restaurant('a3','big')
c.describe_restaurant('a2','small')
c.open_restaurant('a1')
在类中定义函数时,第一参数永远是类的本身实例变量self,并且调用时,不用传递该参数,所以你的方法名应该是这样才对:
def describe_restaurant(self, restaurant_name, cuisine_type)
...
def open_restaurant(self, restaurant_name)
如果对你有帮助请采纳