You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python面向对象程序问题:为何仅执行operation_perform未进入area/perimeter

问题分析与解决方案

为什么程序无法进入area()或perimeter()函数?

  • 你在operation_perform的分支里只是定义了嵌套函数,但从未调用过这些函数。定义函数本身不会执行内部代码,必须显式调用才会触发逻辑。
  • 就算调用了这些函数,代码里的self.a、self.b没有被赋值,会触发AttributeError——你的Shape类没有初始化这些实例属性。
  • 额外错误:矩形面积计算错误地使用了math.pi,正确逻辑应为a * b。

不使用构造函数的实现方案

可以不依赖构造函数,直接在操作分支内处理形状选择、参数输入与计算,修改后的代码如下:

import math

class Shape:
    def operation_perform(self):
        m = input('''
          Select the operation:
          1. Select 1 for area.
          2. Select 2 for perimeter.
          ''')
        
        if m == '1':
            n = input('''
            select the shape:
            1. Select 1 for circle.
            2. Select 2 for square.
            3. Select 3 for rectangular.
            ''')
            # 获取对应形状的参数并计算面积
            if n == '1':
                a = float(input("Enter radius of circle: "))
                print('area of circle: ', math.pi * a**2)
            elif n == '2':
                a = float(input("Enter side length of square: "))
                print('area of square: ', a**2)
            elif n == '3':
                a = float(input("Enter length of rectangular: "))
                b = float(input("Enter width of rectangular: "))
                print('area of rectangular: ', a * b)
            else:
                print("Invalid shape selection")

        elif m == '2':
            n = input('''
              select the shape:
              1. Select 1 for circle.
              2. Select 2 for square.
              3. Select 3 for rectangular.
              ''')
            # 获取对应形状的参数并计算周长
            if n == '1':
                a = float(input("Enter radius of circle: "))
                print('perimeter of circle: ', 2 * math.pi * a)
            elif n == '2':
                a = float(input("Enter side length of square: "))
                print('perimeter of square: ', 4 * a)
            elif n == '3':
                a = float(input("Enter length of rectangular: "))
                b = float(input("Enter width of rectangular: "))
                print('perimeter of rectangular: ', 2*(a + b))
            else:
                print("Invalid shape selection")
        else:
            print("Invalid operation selection")

s = Shape() 
s.operation_perform()

修改说明

  • 移除了嵌套函数定义,直接在操作选择后串联形状选择、参数输入与计算逻辑,避免了未调用函数的问题。
  • 无需构造函数,直接在每个分支内获取用户输入的参数,不依赖实例属性。
  • 修正了矩形面积的计算错误。

内容的提问来源于stack exchange,提问作者傅能杰

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 12:37:10