- 编写程序,创建基类
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()
方法。Rectangle
是Shape
的派生类,新增了length
和width
属性,以及getPerimeter()
和getArea()
方法,用于计算长方形的周长和面积。在测试代码中,创建了一个Rectangle
对象,并通过调用方法来获取和设置属性值,并计算周长和面积。
- 编写程序,创建基类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
是基类,具有brand
和color
属性以及showInfo()
方法用于显示品牌和颜色。Car
是Vehicle
的派生类,新增了seat
属性,并重写了showInfo()
方法来输出所有属性的值。在测试代码中,创建了一个Car
对象,并调用showInfo()
方法来显示车辆的信息,包括品牌、颜色和座位数。
- 题目:设计一个基类
Animal
,具有实例属性name
和实例方法speak()
,用于返回动物的叫声。然后创建两个派生类Dog
和Cat
,分别重写基类的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()
方法。Dog
和Cat
是派生类,分别重写了基类的speak()
方法,实现了狗和猫的叫声。在测试代码中,创建了一个Animal
对象和一个Dog
对象,分别调用它们的name
属性和speak()
方法,以及创建了一个Cat
对象并调用其属性和方法。输出结果为:
Animal
Unknown sound
Buddy
Woof!
Whiskers
Meow!
注意:基类的speak()
方法返回了一个默认的未知声音,派生类通过重写speak()
方法来提供特定的叫声。
- 题目:设计一个基类
Shape
,具有实例属性color
和实例方法get_area()
,用于计算图形的面积。然后创建两个派生类Rectangle
和Circle
,分别重写基类的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()
方法。Rectangle
和Circle
是派生类,分别重写了基类的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
,并具有额外的width
和height
属性。该子类还应该具有一个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
的父类,具有name
和age
属性。然后创建一个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
的父类,具有name
和age
属性。然后创建一个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
,并添加额外的base
和height
属性。该子类还应该重写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环境中运行这些代码,并根据需要进行修改和实验。