我的代码:
class Restaurant():
def init(self, name, foodtype): #创建一个名为Restaurant的类,其方法__init__()设置两个属性:restaurant_name和cuisine_type。
self.name = name
self.foodtype = foodtype
def describe_restaurant(self):
print (self.name.title() + "," + "" + self.foodtype.title())
def open_restaurant (self):
print (self.name.title() + "now is opening.")
调用的时候:
Restaurant1 = Restaurant("Chinese", "Asian food")
print (Restaurant1.describe_restaurant())
Chinese,Asian Food
None
请问下为什么调用了describe_restaurant()会在多出来一个None这一行?
因为你在这个方法里面已经打印了一次,你再打印的话是他的返回值,但是这个方法没有返回值,所以输出None
因为在函数里面print了一次又在实例后print了一次。把函数里面改成return试试
首先print (Restaurant1.describe_restaurant())先执行实例对象的函数调用Restaurant1.describe_restaurant(),调用这个函数时执行函数的语句print (self.name.title() + "," + "" ,,,输出第一行
其次执行最外层print(最后一个print),行为print里面调用了函数,但是函数没有返回值,也就相当于return None所以输出了None
把print改成return即可解决
print (Restaurant1.describe_restaurant())这条语句是多余的,函数里已经print过了,不要函数里函数外都print
五楼说的正确