欢迎访问宙启技术站
智能推送

Python代码生成随机的正方形和矩形形状

发布时间:2023-12-12 03:19:05

下面是一个Python代码生成随机的正方形和矩形形状的例子:

import random

class Shape:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

class Square(Shape):
    def __init__(self, side_length):
        super().__init__(side_length, side_length)

class Rectangle(Shape):
    def __init__(self, width, height):
        super().__init__(width, height)

def generate_random_shapes(num_shapes):
    shapes = []
    for i in range(num_shapes):
        shape_type = random.choice(["square", "rectangle"])
        if shape_type == "square":
            side_length = random.randint(1, 10)
            shape = Square(side_length)
        else:
            width = random.randint(1, 10)
            height = random.randint(1, 10)
            shape = Rectangle(width, height)
        shapes.append(shape)
    return shapes

# 示例用法
shapes = generate_random_shapes(10)
for shape in shapes:
    if isinstance(shape, Square):
        print(f"Square: side length = {shape.width}, area = {shape.area()}")
    elif isinstance(shape, Rectangle):
        print(f"Rectangle: width = {shape.width}, height = {shape.height}, area = {shape.area()}")

以上代码定义了一个Shape类和两个子类SquareRectangle,并在generate_random_shapes函数中生成随机的正方形和矩形形状。Shape类有widthheight属性以及area方法,SquareRectangle类分别继承了Shape类,并分别重写了__init__方法。

generate_random_shapes函数可以接受一个num_shapes参数,用于指定生成的形状数量。函数使用random.choice函数随机选择形状的类型,然后根据形状类型生成对应的形状对象。生成一个正方形时,随机生成一个边长;生成一个矩形时,分别随机生成宽度和高度。将生成的形状对象添加到一个列表中,并在函数最后返回该列表。

在示例用法中,通过调用generate_random_shapes函数生成了10个随机形状。然后遍历这些形状对象,使用isinstance函数判断形状的类型,并根据类型输出相应的信息,包括边长(对于正方形)、宽度、高度和面积。

这个例子向你展示了如何使用Python生成随机的正方形和矩形形状,并通过继承和多态的方式处理不同形状的特定操作。你可以根据自己的需求修改代码,并执行结果进行验证。