Python打卡训练营学习记录Day28

 

题目1:定义圆(Circle)类

要求:

  1. 包含属性:半径 radius。
  2. 包含方法:
  • calculate_area():计算圆的面积(公式:πr²)。
  • calculate_circumference():计算圆的周长(公式:2πr)。
  1. 初始化时需传入半径,默认值为 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)类

  1. 包含属性:长 length、宽 width。
  2. 包含方法:
  • calculate_area():计算面积(公式:长×宽)。
  • calculate_perimeter():计算周长(公式:2×(长+宽))。 is_square() 方法,判断是否为正方形(长 == 宽)。
  1. 初始化时需传入长和宽,默认值均为 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())  

 

@浙大疏锦行 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值