python苹果树代码
时间: 2024-07-17 15:00:36 浏览: 67
在Python中,我们可以使用类和继承的概念来创建一个简单的苹果树模型。以下是一个简单的例子,展示了如何定义一个`Tree`类以及一个派生类`AppleTree`:
```python
class Tree:
def __init__(self, name):
self.name = name
self.fruits = []
def add_fruit(self, fruit):
self.fruits.append(fruit)
print(f"{fruit} added to {self.name}'s tree.")
class AppleTree(Tree):
def __init__(self, name):
super().__init__(name) # 初始化父类(Tree)
self.specialty = "Apples"
def pick_apple(self):
if not self.fruits:
print(f"{self.name}'s {self.specialty} tree is empty.")
else:
apple = self.fruits.pop(0)
print(f"Picked an {apple} from {self.name}'s tree.")
# 使用示例
my_tree = AppleTree("John's")
my_tree.add_fruit("Green Apple")
my_tree.add_fruit("Red Apple")
my_tree.pick_apple()
```
在这个例子中,`AppleTree`继承自`Tree`,并添加了一个特殊的属性`specialty`和一个方法`pick_apple()`。`add_fruit()`方法允许添加任何类型的水果,但`pick_apple()`只针对苹果。
阅读全文