Python_继承——经典题

  1. 编写程序,创建基类Shape,其成员包括实例属性color,实例方法getColor()用于获取实例属性color的值,实例方法setColor()用来设置实例属性color的值;创建派生类Rectange,继承Shape类,新增实例属性length(长)和width(宽),新增实例方法getPerimeter ()getArea()用来分别获取长方形的周长和面积。利用__init__()构造方法完成Shape和Rectange类的对象初始化工作,并编写测试代码。

下面是描述的程序的示例代码:

class Shape:
    def __init__(self, color):
        self.color = color

    def getColor(self):
        return self.color

    def setColor(self, color):
        self.color = color


class Rectangle(Shape):
    def __init__(self, color, length, width):
        super().__init__(color)
        self.length = length
        self.width = width

    def getPerimeter(self):
        return 2 * (self.length + self.width)

    def getArea(self):
        return self.length * self.width


# 测试代码
rectangle = Rectangle("red", 4, 3)
print("Color:", rectangle.getColor())  # 输出:Color: red
print("Perimeter:", rectangle.getPerimeter())  # 输出:Perimeter: 14
print("Area:", rectangle.getArea())  # 输出:Area: 12

rectangle.setColor("blue")
print("New color:", rectangle.getColor())  # 输出:New color: blue

在上述代码中,Shape是基类,具有color属性和getColor()setColor()方法。RectangleShape的派生类,新增了lengthwidth属性,以及getPerimeter()getArea()方法,用于计算长方形的周长和面积。在测试代码中,创建了一个Rectangle对象,并通过调用方法来获取和设置属性值,并计算周长和面积。

  1. 编写程序,创建基类Vehicle,其成员包括实例属性brand(品牌)和color(颜色),实例方法showInfo()用来输出实例属性brand和color的值;创建派生类Car,继承Vehicle类,新增实例属性seat(座位数),重写基类的实例方法showInfo ()输出所有实例属性的值。利用__init__()构造方法完成Vehicle和Car类的对象初始化工作,并编写测试代码。

下面是描述的程序的示例代码:

class Vehicle:
    def __init__(self, brand, color):
        self.brand = brand
        self.color = color

    def showInfo(self):
        print("Brand:", self.brand)
        print("Color:", self.color)


class Car(Vehicle):
    def __init__(self, brand, color, seat):
        super().__init__(brand, color)
        self.seat = seat

    def showInfo(self):
        super().showInfo()
        print("Seat:", self.seat)


# 测试代码
car = Car("Toyota", "Red", 4)
car.showInfo()

在上述代码中,Vehicle是基类,具有brandcolor属性以及showInfo()方法用于显示品牌和颜色。CarVehicle的派生类,新增了seat属性,并重写了showInfo()方法来输出所有属性的值。在测试代码中,创建了一个Car对象,并调用showInfo()方法来显示车辆的信息,包括品牌、颜色和座位数。

  1. 题目:设计一个基类Animal,具有实例属性name和实例方法speak(),用于返回动物的叫声。然后创建两个派生类DogCat,分别重写基类的speak()方法,实现狗和猫的叫声。

以下是示例代码:

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return "Unknown sound"


class Dog(Animal):
    def speak(self):
        return "Woof!"


class Cat(Animal):
    def speak(self):
        return "Meow!"


# 测试代码
animal = Animal("Animal")
print(animal.name)
print(animal.speak())

dog = Dog("Buddy")
print(dog.name)
print(dog.speak())

cat = Cat("Whiskers")
print(cat.name)
print(cat.speak())

在上述代码中,Animal是基类,具有name属性和speak()方法。DogCat是派生类,分别重写了基类的speak()方法,实现了狗和猫的叫声。在测试代码中,创建了一个Animal对象和一个Dog对象,分别调用它们的name属性和speak()方法,以及创建了一个Cat对象并调用其属性和方法。输出结果为:

Animal
Unknown sound
Buddy
Woof!
Whiskers
Meow!

注意:基类的speak()方法返回了一个默认的未知声音,派生类通过重写speak()方法来提供特定的叫声。

  1. 题目:设计一个基类Shape,具有实例属性color和实例方法get_area(),用于计算图形的面积。然后创建两个派生类RectangleCircle,分别重写基类的get_area()方法,实现矩形和圆形的面积计算。

以下是示例代码:

import math

class Shape:
    def __init__(self, color):
        self.color = color

    def get_area(self):
        return 0


class Rectangle(Shape):
    def __init__(self, color, length, width):
        super().__init__(color)
        self.length = length
        self.width = width

    def get_area(self):
        return self.length * self.width


class Circle(Shape):
    def __init__(self, color, radius):
        super().__init__(color)
        self.radius = radius

    def get_area(self):
        return math.pi * self.radius ** 2


# 测试代码
shape = Shape("Blue")
print(shape.color)
print(shape.get_area())

rectangle = Rectangle("Red", 5, 3)
print(rectangle.color)
print(rectangle.length, rectangle.width)
print(rectangle.get_area())

circle = Circle("Green", 2)
print(circle.color)
print(circle.radius)
print(circle.get_area())

在上述代码中,Shape是基类,具有color属性和get_area()方法。RectangleCircle是派生类,分别重写了基类的get_area()方法,实现了矩形和圆形的面积计算。在测试代码中,创建了一个Shape对象和一个Rectangle对象,分别调用它们的color属性和get_area()方法,以及创建了一个Circle对象并调用其属性和方法。输出结果为:

Blue
0
Red
5 3
15
Green
2
12.566370614359172

注意:基类的get_area()方法返回了默认的面积值为0,派生类通过重写get_area()方法来提供特定图形的面积计算逻辑。

练习:

十道关于Python继承的问题,并提供相应的示例代码。

问题1:
创建一个名为Shape的父类,具有一个area方法。然后创建一个Rectangle子类,继承自Shape,并具有额外的widthheight属性。该子类还应该具有一个perimeter方法来计算矩形的周长。

示例代码:

class Shape:
    def area(self):
        pass

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return 2 * (self.width + self.height)

# 示例用法
my_rectangle = Rectangle(5, 3)
print(my_rectangle.area())      # 输出: 15
print(my_rectangle.perimeter()) # 输出: 16

问题2:
创建一个名为Vehicle的父类,具有一个start方法和一个stop方法。然后创建一个Car子类,继承自Vehicle,并具有额外的brand属性。该子类还应该重写start方法,以打印启动汽车的特定消息。

示例代码:

class Vehicle:
    def start(self):
        print("Vehicle started.")

    def stop(self):
        print("Vehicle stopped.")

class Car(Vehicle):
    def __init__(self, brand):
        self.brand = brand

    def start(self):
        print(f"{self.brand} car started.")

# 示例用法
my_car = Car("Toyota")
my_car.start()  # 输出: Toyota car started.
my_car.stop()   # 输出: Vehicle stopped.

问题3:
创建一个名为Person的父类,具有nameage属性。然后创建一个Employee子类,继承自Person,并具有额外的salary属性。该子类还应该重写__str__方法,以返回员工的姓名和薪水。

示例代码:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

class Employee(Person):
    def __init__(self, name, age, salary):
        super().__init__(name, age)
        self.salary = salary

    def __str__(self):
        return f"Employee: {self.name}, Salary: {self.salary}"

# 示例用法
my_employee = Employee("John", 30, 5000)
print(my_employee)  # 输出: Employee: John, Salary: 5000

问题4:
创建一个名为Animal的父类,具有一个sound方法。然后创建一个Cat子类,继承自Animal,并重写sound方法。该子类还应该具有一个claw方法,用于猫抓东西的行为。

示例代码:

class Animal:
    def sound(self):
        print("Animal makes sound")

class Cat(Animal):
    def sound(self):
        print("Meow!")

    def claw(self):
        print("Cat is clawing")



# 示例用法
my_cat = Cat()
my_cat.sound()  # 输出: Meow!
my_cat.claw()   # 输出: Cat is clawing

问题5:
创建一个名为BankAccount的父类,具有balance属性和一个deposit方法。然后创建一个SavingsAccount子类,继承自BankAccount,并添加一个名为interest_rate的属性。该子类还应该重写deposit方法,以在存款时自动计算利息并将其添加到余额中。

示例代码:

class BankAccount:
    def __init__(self, balance=0):
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

class SavingsAccount(BankAccount):
    def __init__(self, balance=0, interest_rate=0):
        super().__init__(balance)
        self.interest_rate = interest_rate

    def deposit(self, amount):
        interest = amount * self.interest_rate
        super().deposit(amount + interest)

# 示例用法
my_savings = SavingsAccount(balance=1000, interest_rate=0.05)
print(my_savings.balance)  # 输出: 1000
my_savings.deposit(500)
print(my_savings.balance)  # 输出: 1575

问题6:
创建一个名为Parent的父类,具有一个parent_method方法。然后创建一个Child子类,继承自Parent,并添加一个名为child_method的方法。该子类还应该重写parent_method方法,以在调用时打印特定的子类消息。

示例代码:

class Parent:
    def parent_method(self):
        print("Parent method")

class Child(Parent):
    def parent_method(self):
        print("Child-specific parent method")

    def child_method(self):
        print("Child method")

# 示例用法
my_child = Child()
my_child.parent_method()  # 输出: Child-specific parent method
my_child.child_method()   # 输出: Child method

问题7:
创建一个名为Fruit的父类,具有一个color属性和一个eat方法。然后创建一个Apple子类,继承自Fruit,并添加一个名为variety的属性。该子类还应该重写eat方法,以打印特定种类的苹果的食用方式。

示例代码:

class Fruit:
    def __init__(self, color):
        self.color = color

    def eat(self):
        print("Eat the fruit")

class Apple(Fruit):
    def __init__(self, color, variety):
        super().__init__(color)
        self.variety = variety

    def eat(self):
        print(f"Eat the {self.variety} apple by biting it.")

# 示例用法
my_apple = Apple("red", "Honeycrisp")
print(my_apple.color)   # 输出: red
print(my_apple.variety)  # 输出: Honeycrisp
my_apple.eat()          # 输出: Eat the Honeycrisp apple by biting it.

问题8:
创建一个名为Animal的父类,具有一个sleep方法。然后创建一个Cat子类,继承自Animal

并添加一个名为hunt的方法。该子类还应该重写sleep方法,以打印猫的特定睡眠方式。

示例代码:

class Animal:
    def sleep(self):
        print("Animal is sleeping")

class Cat(Animal):
    def sleep(self):
        print("Cat is sleeping curled up")

    def hunt(self):
        print("Cat is hunting")

# 示例用法
my_cat = Cat()
my_cat.sleep()  # 输出: Cat is sleeping curled up
my_cat.hunt()  # 输出: Cat is hunting

问题9:
创建一个名为Person的父类,具有nameage属性。然后创建一个Student子类,继承自Person,并添加一个名为grade的属性。该子类还应该重写__str__方法,以返回学生的姓名、年龄和年级。

示例代码:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade

    def __str__(self):
        return f"Student: {self.name}, Age: {self.age}, Grade: {self.grade}"

# 示例用法
my_student = Student("John", 15, 10)
print(my_student)  # 输出: Student: John, Age: 15, Grade: 10

问题10:
创建一个名为Shape的父类,具有一个area方法。然后创建一个Triangle子类,继承自Shape,并添加额外的baseheight属性。该子类还应该重写area方法,以计算三角形的面积。

示例代码:

class Shape:
    def area(self):
        pass

class Triangle(Shape):
    def __init__(self, base, height):
        self.base = base
        self.height = height

    def area(self):
        return 0.5 * self.base * self.height

# 示例用法
my_triangle = Triangle(4, 3)
print(my_triangle.area())  # 输出: 6.0

这是带有独特特点的十道关于Python继承的问题,每道问题都附带了相应的示例代码。您可以尝试在Python环境中运行这些代码,并根据需要进行修改和实验。

  • 5
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值