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

@浙大疏锦行

相关推荐
黑客思维者4 小时前
Python modbus-tk在配电物联网边缘网关的应用
开发语言·python·物联网
郝学胜-神的一滴4 小时前
Separate Buffer、InterleavedBuffer 策略与 OpenGL VAO 深度解析
开发语言·c++·程序人生·算法·游戏程序·图形渲染
裤裤兔4 小时前
python2与python3的兼容
开发语言·python·numpy
一 乐4 小时前
心理健康管理|基于springboot + vue心理健康管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
前端小端长4 小时前
深入理解Composition API与Vue3.0响应式原理
开发语言·javascript
枫叶丹46 小时前
【Qt开发】Qt窗口(九) -> QFontDialog 字体对话框
c语言·开发语言·数据库·c++·qt
海上彼尚7 小时前
Go之路 - 7.go的结构体
开发语言·后端·golang
源代码•宸12 小时前
分布式缓存-GO(分布式算法之一致性哈希、缓存对外服务化)
开发语言·经验分享·分布式·后端·算法·缓存·golang
我送炭你添花12 小时前
Pelco KBD300A 模拟器:03.Pelco-P 协议 8 字节完整拆解 + 与 Pelco-D 一一对应终极对照表
python·测试工具·运维开发