咖啡类:def __init__(self): self._price=4.0 def price(self): return self._price def __str__(self): return \'带有价格的咖啡\'+ str(self._price) 类
class Coffee:
def __init__(self):
self._price=4.0
def price(self):
return self._price
def __str__(self):
return "Coffee with price "+ str(self._price)
class CoffeeWithMilk:
def __init__(self, coffee):
self.price+=coffee.price+0.5
def price(self):
return self.price
coffee=Coffee()
x=CoffeeWithMilk(coffee)
coffeeWithMilk=CoffeeWithMilk(x)
print(coffeeWithMilk)
如何修复?谢谢
coffee.price
是一种 方法 ,因此 coffee.price + 0.5
会出现错误。
如果您想要获取该方法的结果, 请调用 该方法:
self._price = coffee.price() + 0.5
注意,我 +=
在 =
这里替换了,毕竟您正在设置一个新属性。我还 重命名了 该属性,因为否则您的 CoffeeWithMilk.price
方法也会变得非常混乱,导致 第二个 错误,它看起来很相似,因为它 self.price
仍然是一个方法。这需要将 def price(self)
方法修复为:
def price(self):
return self._price
完整的代码如下所示:
class Coffee:
def __init__(self):
self._price = 4.0
def price(self):
return self._price
def __str__(self):
return "Coffee with price " + str(self._price)
class CoffeeWithMilk:
def __init__(self, coffee):
self._price = coffee.price() + 0.5
def price(self):
return self._price
通过使用 price
类继承 来避免重新定义 ;制作 CoffeeWithMilk
一个专门的版本 Coffee
:
class Coffee:
name = 'Coffee'
def __init__(self):
self._price = 4.0
def price(self):
return self._price
def __str__(self):
return "{} with price {}".format(self.name, self._price)
class CoffeeWithMilk(Coffee):
name = 'Coffee with milk'
def __init__(self, coffee):
self._price = coffee.price() + 0.5
你 __str__
也得到了实现,所以你的最终结果 print(coffeeWithMilk)
将输出一些更有趣的东西。
您还可以创建 Coffee.price
一个 property ;属性是每次访问属性时自动调用的方法:
class Coffee:
name = 'Coffee'
def __init__(self):
self._price = 4.0
@property
def price(self):
return self._price
def __str__(self):
return "{} with price {}".format(self.name, self._price)
class CoffeeWithMilk(Coffee):
name = 'Coffee with milk'
def __init__(self, coffee):
self._price = coffee.price + 0.5
但是,在这种情况下,我不会使用方法或属性。这里不需要隐藏 _price
。只需将其替换为直接属性即可:
class Coffee:
name = 'Coffee'
def __init__(self):
self.price = 4.0
def __str__(self):
return "{} with price {}".format(self.name, self.price)
class CoffeeWithMilk(Coffee):
name = 'Coffee with milk'
def __init__(self, coffee):
self.price = coffee.price + 0.5
这是因为方法和属性除了传递 _price
属性之外什么都没做。您也可以直接访问它。
最后但同样重要的一点是,您 CoffeeWithMilk
从一个 Coffee
实例创建一个实例,然后 从第一个 CoffeeWithMilk
另一个 CoffeeWithMilk
,因此您的最终实例将 0.5 添加到 4 两次 :
>>> coffee = Coffee()
>>> x = CoffeeWithMilk(coffee) # first instance, from coffee
>>> print(x)
Coffee with milk with price 4.5
>>> coffeeWithMilk = CoffeeWithMilk(x) # second instance, from x
>>> print(coffeeWithMilk)
Coffee with milk with price 5.0