#原代码如下:
class Restaurant():
"""模拟餐厅"""
def __init__(self,name,type):
"""初始化属性name和age"""
self.name = name
self.type = type
def describe_restaurant(self):
"""介绍restaurant的信息"""
print("restaurant的名字是"+self.name.title()+",类型是"+self.type)
def open_restaurant(self):
"""表示餐厅正在营业"""
print(self.name.title+"正在营业中。")
my_restaurant = Restaurant("伏羲十星","十星级酒店")
my_restaurant.describe_restaurant()
my_restaurant.open_restaurant()
#结果报错:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 12, in open_restaurant
TypeError: unsupported operand type(s) for +: 'builtin_function_or_method' and 'str'
#修改1:在def open_restaurant(self)时,删除print函数中self.name.title的.title,结果运行成功
class Restaurant():
"""模拟餐厅"""
def __init__(self,name,type):
"""初始化属性name和age"""
self.name = name
self.type = type
def describe_restaurant(self):
"""介绍restaurant的信息"""
print("restaurant的名字是"+self.name.title()+",类型是"+self.type)
def open_restaurant(self):
"""表示餐厅正在营业"""
print(self.name+"正在营业中。")
my_restaurant = Restaurant("伏羲十星","十星级酒店")
my_restaurant.describe_restaurant()
my_restaurant.open_restaurant()
>>> class Restaurant():
... """模拟餐厅"""
... def __init__(self,name,type):
... """初始化属性name和age"""
... self.name = name
... self.type = type
... def describe_restaurant(self):
... """介绍restaurant的信息"""
... print("restaurant的名字是"+self.name.title()+",类型是"+self.type)
... def open_restaurant(self):
... """表示餐厅正在营业"""
... print(self.name+"正在营业中。")
...
>>> my_restaurant = Restaurant("伏羲十星","十星级酒店")
>>> my_restaurant.describe_restaurant()
restaurant的名字是伏羲十星,类型是十星级酒店
>>> my_restaurant.open_restaurant()
伏羲十星正在营业中。
#修改2:在def open_restaurant(self)时,用str函数强行把self.name.title换成string,结果失败
>>> class Restaurant():
... """模拟餐厅"""
... def __init__(self,name,type):
... """初始化属性name和age"""
... self.name = name
... self.type = type
... def describe_restaurant(self):
... """介绍restaurant的信息"""
... print("restaurant的名字是"+self.name.title()+",类型是"+self.type)
... def open_restaurant(self):
... """表示餐厅正在营业"""
... print(str(self.name.title)+"正在营业中。")
...
>>> my_restaurant = Restaurant("伏羲十星","十星级酒店")
>>> my_restaurant.describe_restaurant()
restaurant的名字是伏羲十星,类型是十星级酒店
>>> my_restaurant.open_restaurant()
<built-in method title of str object at 0x000001FBB2493690>正在营业中。
我想请问一下,为什么用self.name.title会出错,以及同样是self.name.title,同样是print函数,describe_restaurant(self)就不受影响,而open_restaurant(self)就会出错?多谢啦~