Python子类苹果梨,继承父类苹果和梨
时间: 2023-08-14 14:12:49 浏览: 102
可以通过多重继承来实现Python子类苹果梨,继承父类苹果和梨的属性和方法。示例代码如下:
```python
class Apple:
def __init__(self, color):
self.color = color
self.type = 'apple'
def eat(self):
print("This apple is delicious!")
class Pear:
def __init__(self, shape):
self.shape = shape
self.type = 'pear'
def eat(self):
print("This pear is juicy!")
class ApplePear(Apple, Pear):
def __init__(self, color, shape):
Apple.__init__(self, color)
Pear.__init__(self, shape)
def eat(self):
print("This apple-pear is both delicious and juicy!")
fruit = ApplePear('red', 'round')
print(fruit.color) # output: red
print(fruit.shape) # output: round
print(fruit.type) # output: apple
fruit.eat() # output: This apple-pear is both delicious and juicy!
```
在这个例子中,我们定义了两个父类 Apple 和 Pear,它们都有一个 eat() 方法和一些属性。然后我们定义了一个子类 ApplePear,它继承了父类 Apple 和 Pear,并且实现了自己的 eat() 方法。在 ApplePear 的构造函数中,我们调用了父类的构造函数来初始化父类的属性。最后我们创建了一个 ApplePear 对象 fruit,打印出了它的属性,并调用了 eat() 方法。
阅读全文