1、 创建球类。属性包括球的半径和颜色,计算球体的面积和体积、
2、 设计一个Person(人)类,包括姓名,年龄,和血型属性,编写构造方法,用于初始化每个人的具体属性,编写detail方法用于输出每个实例具体值。
3、 设计一个Animal(动物)类,包括颜色属性和叫方法,再设计一个Fish类(鱼)类。包括尾巴和颜色两个属性,以及叫法。要求:Fish类继承自Animal类,重写构造方法和叫方法
class Sphere:
def __init__(self, radius, color):
self.radius = radius
self.color = color
def area(self):
return 4 * 3.14 * self.radius ** 2
def volume(self):
return 4 / 3 * 3.14 * self.radius ** 3
# 示例
my_sphere = Sphere(2, "red")
print(my_sphere.color)
print(my_sphere.area())
print(my_sphere.volume())
Person类实现
class Person:
def __init__(self, name, age, blood_type):
self.name = name
self.age = age
self.blood_type = blood_type
def detail(self):
print("Name: ", self.name)
print("Age: ", self.age)
print("Blood type: ", self.blood_type)
# 示例
my_person = Person("Tom", 30, "O")
my_person.detail()
Animal类和Fish类实现
class Animal:
def __init__(self, color):
self.color = color
def call(self):
print("Animal sound")
class Fish(Animal):
def __init__(self, color, tail, call_sound):
super().__init__(color)
self.tail = tail
self.call_sound = call_sound
def call(self):
print(self.call_sound)
# 示例
my_fish = Fish("pink", "large", "Bloop")
print(my_fish.color)
print(my_fish.tail)
my_fish.call()
注意,在Fish类中,我们使用了super()函数来调用父类的构造方法,在Fish类中添加了新的属性tail,并且重写了call方法。