DAY 28 类的定义和方法

题目1:定义圆(Circle)类 要求: 1.包含属性:半径 radius。 2.包含方法: ●calculate_area():计算圆的面积(公式:πr²)。 ●calculate_circumference():计算圆的周长(公式:2πr)。 3.初始化时需传入半径,默认值为 1。

import math

class Circle:
    def __init__(self, radius=1):
        self.radius = radius
    
    def calculate_area(self):
        return math.pi * (self.radius ** 2)
    
    def calculate_circumference(self):
        return 2 * math.pi * self.radius

题目2:定义长方形(Rectangle)类 1.包含属性:长 length、宽 width。 2.包含方法: ●calculate_area():计算面积(公式:长×宽)。 ●calculate_perimeter():计算周长(公式:2×(长+宽))。 is_square() 方法,判断是否为正方形(长 == 宽)。 3.初始化时需传入长和宽,默认值均为 1。

class Rectangle:
    def __init__(self, length=1, width=1):
        self.length = length
        self.width = width
    
    def calculate_area(self):
        return self.length * self.width
    
    def calculate_perimeter(self):
        return 2 * (self.length + self.width)
    
    def is_square(self):
        return self.length == self.width

题目3:图形工厂 创建一个工厂函数 create_shape(shape_type, *args),根据类型创建不同图形对象:图形工厂(函数或类) shape_type="circle":创建圆(参数:半径)。 shape_type="rectangle":创建长方形(参数:长、宽)。

def create_shape(shape_type, *args):
    if shape_type == "circle":
        # 圆:只需一个参数(半径)
        if len(args) == 0:
            return Circle()  # 使用默认半径
        elif len(args) == 1:
            return Circle(args[0])
        else:
            raise ValueError("Circle requires 0 or 1 argument (radius)")
    
    elif shape_type == "rectangle":
        # 长方形:需要0-2个参数(长和宽)
        if len(args) == 0:
            return Rectangle()  # 使用默认长宽
        elif len(args) == 1:
            return Rectangle(args[0], args[0])  # 正方形
        elif len(args) == 2:
            return Rectangle(args[0], args[1])
        else:
            raise ValueError("Rectangle requires 0 to 2 arguments (length, width)")
    
    else:
        raise ValueError(f"Unsupported shape type: {shape_type}")

@浙大疏锦行

你可能感兴趣的:(python,算法,开发语言)