class Restaurant:
def __init__(self,restaurant_name,cuisine_type,**others):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
for other in others.keys():
self.other = others[other]
def describe_restaurant(self):
print(f"The {self.restaurant_name} provides {self.cuisine_type} , deilicious!")
def open_restaurant(self):
print(f"The {self.restaurant_name} is opening")
my_restaurant = Restaurant(restaurant_name='QIN',cuisine_type='China',color='black',shuaiqi='yes')
print(my_restaurant.shuaiqi)
为什么这样会错误呢,求解答
print(my_restaurant.other)
这样却是正确的
因为你定义了self.other而不是self.shuaiqi,所以属性名就是other而不是shuaiqi。
可以把self.other = others[other]改为setattr(self, other, others[other]),这样color和shuaiqi就会作为属性名。
参看:python学习之初始化实例、类属性、方法_刘炫320的博客-CSDN博客_python初始化属性的方法
我好像想明白了,是因为这个other是个变量名吧,没有把我想要的给指向出来,但是如果想弄成我想要的结果该怎么做呢