子类继承之后添加新的属性出现报错及解决方法

在进行继承相关代码练习的时候,遇到了子类进行继承之后,添加新的属性提示报错的情况,原始代码如下:

 1 class Restaurant():
 2     """定义父类"""
 3     def __init__(self, restaurant_name, cuisine_type):
 4         '''初始化餐厅的两个属性'''
 5         self.restaurant_name = restaurant_name
 6         self.cuisine_type = cuisine_type
 7         self.number_served = 50
 8 
 9     def describe_restaurant(self):
10         print("餐厅名字为%s, 餐厅类型为%s" % (self.restaurant_name, self.cuisine_type))
11 
12     def open_restaurant(self):
13         print("We are open now, Welcome!")
14 
15     def set_number_served(self, num):
16         self.number_served = num
17 
18     def increment_number_served(self, incre_num):
19         return incre_num
20 
21 
22 class IceCreamStand(Restaurant):
23     """定义子类"""
24     def __init__(self, restaurant_name, cuisine_type, flavors):
25         super().__init__(restaurant_name, cuisine_type)
26         self.flavors = flavors
27 
28     def taste(self):
29         print("我喜欢的冰激凌的口味是%s" % IceCreamStand.flavors)
30 
31 
32 my_faver = IceCreamStand("哈根达斯", "甜品店", "抹茶味")
33 my_faver.describe_restaurant()
34 my_faver.taste()

运行时出现报错提示子类没有”flavors“这个属性

AttributeError: type object 'IceCreamStand' has no attribute 'flavors'

经过网上一顿冲浪之后,发现大佬们给出的解决方法是在进行继承的时候,子类中的参数(形参)的数量要跟父类保持一致,即有如下两种写法:

 1 class IceCreamStand(Restaurant):
 2     """定义子类"""
 3     def __init__(self, restaurant_name, cuisine_type):
 4         super().__init__(restaurant_name, cuisine_type)
 5         self.flavors = "抹茶味"
 6 
 7     def taste(self):
 8         print("我喜欢的冰激凌的口味是%s" % IceCreamStand.flavors)
 9 
10 
11 my_faver = IceCreamStand("哈根达斯", "甜品店")
12 my_faver.describe_restaurant()
13 my_faver.taste()

或者

 1 class IceCreamStand(Restaurant):
 2     """定义子类"""
 3     def __init__(self, restaurant_name, cuisine_type, flavors="抹茶味"):
 4         super().__init__(restaurant_name, cuisine_type)
 5         self.flavors = flavors
 6 
 7     def taste(self):
 8         print("我喜欢的冰激凌的口味是%s" % IceCreamStand.flavors)
 9 
10 
11 my_faver = IceCreamStand("哈根达斯", "甜品店")
12 my_faver.describe_restaurant()
13 my_faver.taste()

结果发现按照大佬的方法修改之后仍然提示没有这个属性,这就有点难受。你说这孩子,给你加个属性,让你青出于蓝而胜于蓝咋就怎么难呢?

再次检查了报错的行数第8行之后,终于发现我在使用属性的时候,直接写了IceCreamStand这个类名。。。而这里在类内部定义的时候,应该是要用self来代替类的实例

哎,还是代码写的太少了,想当然的就直接使用了目标的类名。

修改为self之后,问题解决。

餐厅名字为哈根达斯, 餐厅类型为甜品店
我喜欢的冰激凌口味是抹茶味

总结

这段原始的代码中其实总共有两处错误:

1.就是大佬们指出的那种继承时,子类的形参数量与父类没有保持一致的情况。

如果只有这个错误的话,其报错内容应该是参数数量问题:

TypeError: __init__() takes 2 positional arguments but 3 were given

但是可能由于我的第二个问题更先执行到,上面这个报错就没有展示

2.在类内部使用属性或方法的时候,应该是要用私有类self来代替目标类的实例。

这个错误比较低级,因为类的定义过程是比较约定成俗的,里面的一些规则都是固定的,

因此这个问题是由于自己不够熟悉类的定义和实例化过程导致的,以后应当吸取教训。

最懒的人就是整天忙得没时间学习、反思、成长的人。
原文地址:https://www.cnblogs.com/jockeyhao/p/13674434.html