import math

class Circle:
    def __init__(self, radius):
        if radius < 0:
            raise ValueError('半径不能为负数')
        self.radius = radius

    def area(self):
        return math.pi * self.radius ** 2

try:
    c1 = Circle(3)
    print(c1.area())
    c2 = Circle(-2)
    print(c2.area())
except ValueError as e:
    print(e)

输出:

28.274333882308138
半径不能为负数
Python计算圆的面积并处理负半径异常

原文地址: https://www.cveoy.top/t/topic/mMPG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录