Python 小鸟飞行模拟代码示例
以下是一段使用 Python 编写的小鸟飞行代码示例:
class Bird:
def __init__(self, name, speed):
self.name = name
self.speed = speed
self.distance = 0
def fly(self, time):
self.distance = self.speed * time
def print_distance(self):
print(f'The bird {self.name} has flown a distance of {self.distance} units.')
# 创建小鸟对象
bird1 = Bird('Sparrow', 10)
bird2 = Bird('Eagle', 20)
# 飞行
bird1.fly(5)
bird2.fly(10)
# 打印飞行距离
bird1.print_distance()
bird2.print_distance()
运行上述代码,输出结果如下:
The bird Sparrow has flown a distance of 50 units.
The bird Eagle has flown a distance of 200 units.
这段代码定义了一个名为'Bird'的类,具有'name'、'speed'和'distance'三个属性。'fly'方法接受一个时间参数,并根据速度计算鸟飞行的距离。'print_distance'方法用于打印鸟已经飞行的距离。
在示例中,创建了两只鸟'bird1'和'bird2',分别设置了它们的名称和速度。然后,调用'fly'方法模拟鸟的飞行,传入不同的时间参数。最后,使用'print_distance'方法打印每只鸟已经飞行的距离。
原文地址: https://www.cveoy.top/t/topic/pBRx 著作权归作者所有。请勿转载和采集!