Q2581125112 2022-02-06 22:44 采纳率: 85.7%
浏览 23
已结题

python中类为什么不可以这样输入任意数量的属性呢


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)
这样却是正确的

  • 写回答

2条回答 默认 最新

  • SmallAntJ 2022-02-06 22:58
    关注

    因为你定义了self.other而不是self.shuaiqi,所以属性名就是other而不是shuaiqi。
    可以把self.other = others[other]改为setattr(self, other, others[other]),这样color和shuaiqi就会作为属性名。
    参看:python学习之初始化实例、类属性、方法_刘炫320的博客-CSDN博客_python初始化属性的方法

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 2月14日
  • 已采纳回答 2月6日
  • 创建了问题 2月6日