Day 30 类的定义与方法

类(Class):定义了一类事物的共同属性(比如人的姓名、年龄)和行为(比如走路、说话)

对象 / 实例(Object/Instance):类的具体存在,比如 "张三" 是 "人" 这个类的一个实例

属性(Attribute) :类 / 对象的特征(变量),比如nameage

方法(Method) :类 / 对象的行为(函数),比如walk()speak()

构造方法__init__,创建对象时自动执行,用于初始化属性。

python 复制代码
import math
class Circle:
    def __init__(self,radius):
        self.radius = radius
    def calculate_area(self,radius):
        area = math.pi * (radius **2)
        print(f"半径为{radius}的圆的面积:{area:.2f}") 
    def calculate_circumference(self,radius):
        circumference = 2 * math.pi * radius
        print(f"半径为{radius}的圆的周长:{circumference:.2f}")
circle = Circle(5)
print(f"圆的半径:{circle.radius}")
circle.calculate_area(circle.radius)
circle.calculate_circumference(circle.radius)
python 复制代码
class Rectangle:
    def __init__(self,length,width):
        self.length = length
        self.width = width
    def calculate_area(self,length,width):
        area = length * width
        print(f"长为{length},宽为{width}的矩形的面积:{area}")
    def calculate_perimeter(self,length,width):
        perimeter = 2 * (length + width)
        print(f"长为{length},宽为{width}的矩形的周长:{perimeter}")
    def is_square(self,length,width):
        if length == width:
            return True
        else:
            return False

rectangle = Rectangle(4,6)
print(f"矩形的长:{rectangle.length},宽:{rectangle.width}")
rectangle.calculate_area(rectangle.length,rectangle.width)
rectangle.calculate_perimeter(rectangle.length,rectangle.width)

Square = Rectangle(5,5)
print(f"是否为正方形:{Square.is_square(Square.length,Square.width)}")
python 复制代码
def create_shape(shape_type, *args):
    if shape_type == "circle":
        return Circle(*args)
    elif shape_type == "rectangle":
        return Rectangle(*args)
    else:
        raise ValueError("Unknown shape type")

shape1 = create_shape("circle", 5)
print(shape1.calculate_circumference(5))  

shape2 = create_shape("rectangle", 3, 4)
print(shape2.is_square(3,4)) 

@浙大疏锦行

相关推荐
IVEN_2 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang3 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮4 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling4 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮7 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽7 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers