Python继承错误(带有私有变量)
我是一名编码初学者,尝试查找错误,但找不到出现错误的原因。有人能给我解释一下吗 我的代码如下:Python继承错误(带有私有变量),python,inheritance,Python,Inheritance,我是一名编码初学者,尝试查找错误,但找不到出现错误的原因。有人能给我解释一下吗 我的代码如下: class Automobile: __material = None __height = None __width = None __engine_size = None def set_values(self, mat, height, width, engsz="M"): self.__material =
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 self.getWidth * self.getHeight * self.__findPricePerUnit
print("A new car is being made")
print("What are the dimensions wanted for the new car in")
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)
我对此的意见是:
铁=10,钢=20,金=50,钻石=100
金
1.5
5.
最后显示的输出为:
制造了一辆新车!
这辆新车的价格是:
我不太清楚为什么会出现这种情况,有人能给我解释一下吗
print("A new car has been made!")
print("The price of this new car is: ")
print(car1.price())
因为price()是一种方法。代码中有几个错误,其中一些错误如下:
car1.price()
priceDict
,因此中也会出现错误
price
不是属性,而是方法(函数)。因此,您必须调用它,即price()
。在您的情况下,最好使用(可缓存)属性。如果您搜索“Python属性”,您会发现更多。PS:Python不像其他更严格的语言那样具有私有属性。您还应该避免混合命名约定;python通常使用蛇形外壳,因此get_height
,get_width
,等等(或者只是width()
或height()
-或者因为它们只是属性,.width
和.height
更可取。在Python中使用getter和setter不像在Java和类似语言中那样常见,因为如果需要,可以稍后将其包装为getter/setter对。在类中定义的属性也是类属性,不会被破坏self.
中给出的属性的t值。修复了它,谢谢!
def price(self):
return self.getWidth() * self.getHeight() * self.__findPricePerUnit()