Python类继承(含私有变量)调用方法输出bound method问题求解
问题原因及修复方案
直接异常输出原因
你看到的<bound method Car.price of ...>输出,核心原因是调用类实例方法时没有添加括号:
- 代码最后一行写的是
print(car1.price),price是Car类定义的实例方法,不加括号不会执行方法内部逻辑,只会返回方法对象本身的描述信息,这是当前输出异常的直接诱因。
代码中存在的其他隐藏问题
即使给price加上括号,代码依然会报错,还有几个问题需要同步修复:
- 所有实例方法调用都遗漏了括号:
self.getMat、self.getWidth、self.getHeight都是类的实例方法,必须加()才能拿到返回值,否则都是方法对象,无法参与运算或者作为字典的键使用。 - 缺少
priceDict变量的定义逻辑:你输入的第一行是材质和价格的映射关系,但代码中没有接收这行输入、解析生成字典的逻辑,直接使用priceDict会报变量未定义错误。 - 输入的尺寸是字符串类型:
input()函数返回的结果默认是字符串类型,直接拿height和width相乘会报类型错误,需要转换成数值类型(float/int)。 - 价格计算逻辑中方法调用错误:
__findPricePerUnit方法中return priceDict[self.getMat]需要改成return priceDict[self.getMat()],price方法里的self.getWidth * self.getHeight需要改成float(self.getWidth()) * float(self.getHeight())。
修正后的完整代码
class Automobile: __material = None __height = None __width = None __engine_size = None def set_values(self, mat, height, width, engsz="M"): self.__material = mat self.__height = height self.__width = width self.__engine_size = engsz def getMat(self): return self.__material def getHeight(self): return self.__height def getWidth(self): return self.__width def getEngineSize(self): return self.__engine_size class Car(Automobile): __pricePU = None def __findPricePerUnit(self): return priceDict[self.getMat()] def price(self): return float(self.getWidth()) * float(self.getHeight()) * self.__findPricePerUnit() print("A new car is being made") print("What are the dimensions wanted for the new car in") # 新增解析价格字典的逻辑 price_input = input("Enter material price map(format: iron=10,steel=20...): ") priceDict = {} for item in price_input.split(','): k, v = item.split('=') priceDict[k.strip()] = int(v.strip()) mat = input("Enter material: ") height = input("Enter height: ") width = input("Enter width: ") car1 = Car() car1.set_values(mat, height, width) print("A new car has been made!") print("The price of this new car is: ") # 调用方法添加括号 print(car1.price())
对应测试输入的运行结果
你给出的测试输入运行修正后的代码,输出结果为375.0(计算逻辑:1.5 * 5 * 50 = 375)。
内容的提问来源于stack exchange,提问作者Abs.hek
相关产品推荐
相关产品推荐

