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

@浙大疏锦行

相关推荐
2501_944711432 分钟前
JS 对象遍历全解析
开发语言·前端·javascript
凡人叶枫28 分钟前
C++中智能指针详解(Linux实战版)| 彻底解决内存泄漏,新手也能吃透
java·linux·c语言·开发语言·c++·嵌入式开发
Tony Bai28 分钟前
再见,丑陋的 container/heap!Go 泛型堆 heap/v2 提案解析
开发语言·后端·golang
小糯米6011 小时前
C++顺序表和vector
开发语言·c++·算法
froginwe111 小时前
JavaScript 函数调用
开发语言
阔皮大师1 小时前
INote轻量文本编辑器
java·javascript·python·c#
独望漫天星辰1 小时前
C++ 多态深度解析:从语法规则到底层实现(附实战验证代码)
开发语言·c++
小法师爱分享1 小时前
StickyNotes,简单便签超实用
java·python
深蓝电商API1 小时前
处理字体反爬:woff字体文件解析实战
爬虫·python
开源技术1 小时前
Claude Opus 4.6 发布,100万上下文窗口,越贵越好用
人工智能·python