我使用python编写了以下脚本:
class Fruit:
def __init__(self,name):
self.name = name
print "Initialized Fruit Name: %s" % self.name
def tell(self):
print "U have entered the fruit as %s" % self.name
class Sweet(Fruit):
def __init__(self,name,taste,price):
Fruit.__init__(self,name)
self.taste = taste
print "Initialized the name of the fruit as %s" % self.name
def tell(self):
Fruit.tell(self)
print "Taste of the fruit is %s" % self.taste
def sayPrice(self):
Fruit.tell(self)
print "The price of the fruit Mango is %d" % self.price
class Salt(Fruit):
def __init__(self,name,taste,price):
Fruit.__init__(self,name)
self.taste = taste
print "Initialized the name of the fruit as %s" % self.name
def tell(self):
Fruit.tell(self)
print "Taste of the fruit is %s" % self.taste
def sayPrice(self):
Fruit.tell(self)
print "The price of the fruit Strawberry is %d" % self.price
m = Sweet('Mango','sweet',100)
s = Salt('Strawberry','salty',50)
choice = raw_input("enter ur choice:(Mango/Strawberry):")
if choice == 'Mango':
m.tell()
else:
s.tell()
decision = raw_input("Do U want to know the price?(Y/N)")
if decision == 'Y' and choice == 'Mango':
m.sayPrice()
elif decision == 'Y' and choice == 'Strawberry':
s.sayPrice()
else:
print "Sad to see U go :(, please do visit next time again"
以下是我得到的错误:
追踪(最近一次呼叫最后一次):
文件“C:/Python26/Inheritance_practice2.py”,第47行,
m.sayPrice()
文件“C:/Python26/Inheritance_practice2.py”,第21行,在sayPrice
print "The price of the fruit Mango is %d" % self.price
AttributeError:Sweet实例没有属性'price'
注意:当用户想知道价格时,会抛出错误 选择的水果。
答案 0 :(得分:4)
self.price=price
方法中需要__init__
- 目前您只是抛弃了该参数。
答案 1 :(得分:2)
您需要添加self.price
,最好添加到Fruit
:
class Fruit:
def __init__(self,name,price):
self.name = name
self.price = price #set price when initiated.
(...)
class Sweet(Fruit):
def __init__(self,name,taste,price):
Fruit.__init__(self,name,price) #send price as init parameter
self.taste = taste
print "Initialized the name of the fruit as %s" % self.name
(..)
答案 2 :(得分:1)
也许是一个更好的选择将该属性添加到您的父类水果
class Fruit:
def __init__(self,name, price):
self.name = name
self.price = price
print "Initialized Fruit Name: %s" % self.name
def tell(self):
print "U have entered the fruit as %s" % self.name
class Sweet(Fruit):
def __init__(self,name,taste,price):
Fruit.__init__(self,name, price)
self.taste = taste
print "Initialized the name of the fruit as %s" % self.name
def tell(self):
Fruit.tell(self)
print "Taste of the fruit is %s" % self.taste
def sayPrice(self):
Fruit.tell(self)
print "The price of the fruit Mango is %d" % self.price
class Salt(Fruit):
def __init__(self,name,taste,price):
Fruit.__init__(self,name, price)
self.taste = taste
print "Initialized the name of the fruit as %s" % self.name
def tell(self):
Fruit.tell(self)
print "Taste of the fruit is %s" % self.taste
def sayPrice(self):
Fruit.tell(self)
print "The price of the fruit Strawberry is %d" % self.price
也可以正常工作。您还可以在Fruit类中添加一个getter来获取价格,保存代码行并使用OOP给出的优势,因为您的子类继承了该方法