题目1:定义圆(Circle)类
要求:
- 包含属性:半径 radius。
- 包含方法:
- calculate_area():计算圆的面积(公式:πr²)。
- calculate_circumference():计算圆的周长(公式:2πr)。
- 初始化时需传入半径,默认值为 1。
class Circle:
def __init__(self, radius=1):
self.radius = radius
def caluculate_area(self):
area = 3.14 * self.radius * self.radius
print(f"圆的面积为{area:.2f}")
def caluculate_circumference(self):
circumference = 3.14 * 2 * self.radius
print(f"圆的周长为{circumference:.2f}")
# 现在可以传入半径参数
Circle_instance = Circle(10)
Circle_instance.caluculate_area()
Circle_instance.caluculate_circumference()
题目2:定义长方形(Rectangle)类
- 包含属性:长 length、宽 width。
- 包含方法:
- calculate_area():计算面积(公式:长×宽)。
- calculate_perimeter():计算周长(公式:2×(长+宽))。 is_square() 方法,判断是否为正方形(长 == 宽)。
- 初始化时需传入长和宽,默认值均为 1。
from cmath import rect
class Rectangle:
def __init__(self, width=1, height=1):
self.width = width
self.height = height
def caluculate_area(self):
area = self.width * self.height
print(f"矩形的面积为{area:.2f}")
def caluculate_perimeter(self):
perimeter = 2 * (self.width + self.height)
print(f"矩形的周长为{perimeter:.2f}")
def is_square(self):
if self.width == self.height:
print("是否为正方形:Ture")
else:
print("是否为正方形:False")
rect = Rectangle(4, 26)
rect.caluculate_area()
rect.caluculate_perimeter()
rect.is_square()
题目3:图形工厂
创建一个工厂函数 create_shape(shape_type, *args),根据类型创建不同图形对象:图形工厂(函数或类)
shape_type="circle":创建圆(参数:半径)。
shape_type="rectangle":创建长方形(参数:长、宽)。
import math
class Circle:
def __init__(self, radius):
self.radius = radius
def calculate_circumference(self):
return round(2 * math.pi * self.radius, 2)
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def is_square(self):
return self.length == self.width
def create_shape(shape_type, *args):
if shape_type == "circle":
return Circle(*args)
elif shape_type == "rectangle":
return Rectangle(*args)
else:
raise ValueError("Unsupported shape type")
shape1 = create_shape("circle", 5)
print(shape1.calculate_circumference())
shape2 = create_shape("rectangle", 3, 4)
print(shape2.is_square())