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)) 

@浙大疏锦行

相关推荐
睡美人的小仙女1275 小时前
Threejs加载环境贴图报错Bad File Format: bad initial token
开发语言·javascript·redis
rayufo5 小时前
【工具】列出指定文件夹下所有的目录和文件
开发语言·前端·python
RANCE_atttackkk5 小时前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea
缺点内向6 小时前
C#编程实战:如何为Word文档添加背景色或背景图片
开发语言·c#·自动化·word·.net
一起养小猫6 小时前
Flutter for OpenHarmony 实战:记账应用数据统计与可视化
开发语言·jvm·数据库·flutter·信息可视化·harmonyos
zhougl9966 小时前
Java 所有关键字及规范分类
java·开发语言
Python 老手6 小时前
Python while 循环 极简核心讲解
java·python·算法
java1234_小锋6 小时前
Java高频面试题:MyISAM索引与InnoDB索引的区别?
java·开发语言
2501_944525546 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 支出分析页面
android·开发语言·前端·javascript·flutter
qq_417129257 小时前
C++中的桥接模式变体
开发语言·c++·算法