Python打卡训练营day28-类的定义与方法

发布于:2025-05-22 ⋅ 阅读:(25) ⋅ 点赞:(0)

知识点回顾:

  1. 类的定义
  2. pass占位语句
  3. 类的初始化方法
  4. 类的普通方法
  5. 类的继承:属性的继承、方法的继承

类的定义,初始化,方法

即将“对象”和可以对“对象”进行的“操作”封装到一起

import math  

class Circle:  # 定义一个类
    def __init__(self, radius=1): # 传入半径
        self.radius = radius      # self.radius 是实例属性(可修改属性名,需同步改方法中的用)

    def calculate_area(self):              # 定义面积方法
        return math.pi * self.radius ** 2  # math.pi 是固定常量,self.radius 是实例属性

    def calculate_circumference(self):     # 定义周长方法
        return 2 * math.pi * self.radius

cir1 = Circle(5)
print(cir1.calculate_area())
print(cir1.calculate_circumference())

78.53981633974483

31.41592653589793

方形类

class Rectangle:
    def __init__(self,length,width):
        self.length = length
        self.width = width

    def calculate_area(self):
        return 2*(self.length+self.width)
    
    def calculate_perimeter(self):
        return self.length * self.width
    
    def is_square(self):
        if self.length == self.width:
            return True
        else:
            return False
rect1 = Rectangle(2,2)
print(rect1.calculate_area())
print(rect1.calculate_perimeter())
rect1.is_square()

8

4

True

工厂函数

def create_shape(shape_type, *args):
    # 根据类型创建对应的图形对象
    if shape_type == "circle":
        return Circle(*args)      # 创建圆,传入半径参数
    elif shape_type == "rectangle":
        return Rectangle(*args)   # 创建长方形,传入长和宽
    else:
        raise ValueError("Invalid shape type. Supported types: 'circle', 'rectangle'")

pass

用于类或方法暂时没有具体实现时,用 pass 避免语法错误:

class EmptyClass:  # 空类(占位)
    pass

def todo_method():  # 待实现的方法
    pass

类的继承

class Rectangle:
    def __init__(self,length,width):
        self.length = length
        self.width = width

    def calculate_area(self):
        return 2*(self.length+self.width)
    
    def calculate_perimeter(self):
        return self.length * self.width
    
    def is_square(self):
        if self.length == self.width:
            return True
        else:
            return False

class square:
    def __init__(self,width):
        super().__init__(width)        # 继承初始化方法

    def calculate_area(self):
        return self.width*self.width   # 重写面积函数


网站公告

今日签到

点亮在社区的每一天
去签到