Mobile wallpaper 1
163 字
1 分钟
Python笔记 | 第8章 面向对象/编程题2
2024-12-16

1.创建一个类Animal,包含属性name和方法speak,在创造子类Dog和Cat,分别重新speak方法打印‘汪汪汪’和‘喵喵喵’。

class Animal:
def __init__(self,name):
self.name=name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return '汪汪汪'
class Cat(Animal):
def speak(self):
return '喵喵喵'
dog=Dog('旺财')
cat=Cat('鱼干')
print(dog.speak())
print(cat.speak())

2.创建一个类Shape,包含属性color和方法draw,再创建子类Circle和Rectangle,分别实现draw方法打印对应颜色的圆形和矩形。

class Shape:
def __init__(self,color):
self.color=color
def draw(self):
pass
class Circle(Shape):
def draw(self):
return f'绘制一个{self.color}的圆形'
class Rectangle(Shape):
def draw(self):
return f'绘制一个{self.color}的矩形'
circle=Circle('红色')
rectangle=Rectangle('蓝色')
print(circle.draw())
print(rectangle.draw())
Python笔记 | 第8章 面向对象/编程题2
https://szh.rainettle.top/posts/python_notes2/
作者
SuzuhaYuki
发布于
2024-12-16
许可协议
CC BY-NC-SA 4.0