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

Python自定义Polynomia1类仅1个函数有输出,无法进入degree等方法求助

问题原因
  • 未主动调用目标方法:当前代码仅执行了print(Polynomia1([(3, 5)]))逻辑,该操作只会触发类的__str__方法,你没有主动调用degree和coefficient方法,自然不会进入对应执行逻辑。
  • 方法命名不符合Python规范:你定义的__degree__方法使用了前后双下划线的命名格式,Python会对双下划线开头的类成员做名称修饰,该方法会被自动重命名为_Polynomia1__degree__,直接调用实例.__degree__()会提示方法不存在,无法进入执行逻辑。这类双下划线命名是Python魔法方法的专用格式,不建议自定义普通方法使用。
  • coefficient方法逻辑错误:方法内的return语句缩进层级错误,被放在了for循环内部,第一次循环无论是否匹配到对应次数都会直接返回结果,循环永远只会执行一次。
  • 额外注意:你定义的类名是Polynomia1,末尾是数字1而非字母L,调用时不要写错。
修复方案
  1. 将__degree__改名为普通方法名degree,避免名称修饰问题。
  2. 调整coefficient方法的return语句缩进,放到for循环结束之后,保证遍历完所有项再返回结果。
  3. 实例化类之后主动调用对应方法验证逻辑。
修正后可运行代码示例
class Polynomia1:
    def __init__(self, data=[]):
        if len(data) > 0:
            data = sorted(data, key=lambda x: x[0])
            data.reverse()
            b= []
            for elem in data:
                if elem[0] < 0:
                    raise ValueError("Negative power is not allowed")
                if elem[0] >= 0:
                    b.append(elem[0])
                if elem[1] == 0:
                    raise ValueError("coefficient cannot be empty")
            if len(data) > len(set(b)):
                raise ValueError("The value of power cannot be repeated")
        self.data = data
    def create_equation(self):
        a = ""
        if len(self.data) == 0:
            a+= '0'
        else:
            for num in self.data:
                if num[0] != 0 and num[0] != 1 and num[1] != 1 and num[1] != -1:
                    if len(a) == 0 or num[1] < 0:
                        a += f'{num[1]}x^{num[0]}'
                    else:
                        a += f'+{num[1]}x^{num[0]}'
                if num[1] == -1 and num [0] != 0 and num[0] != 1:
                    a += f'-x^{num[0]}'
                if num[1] == 1 and num [0] != 0 and num[0] != 1 and len(a) > 0:
                    a += f'+x^{num[0]}'
                if num[1] == 1 and num [0] != 0 and num[0] != 1 and len(a) == 0:
                    a += f'x^{num[0]}'              
                if (len(a) == 0 or num[1] <=0)and num[0] == 0:
                    a += str(num[1])
                if len(a) > 0 and num[1] > 0 and num[0] == 0:
                    a += f'+{num[1]}'
                if ((len(a) == 0 or num[1] <=0) and num[1] != -1 and num[1]!=1) and num[0] == 1:
                    a += f'{num[1]}x'
                if ((len(a) == 0 or num[1] <=0) and num[1] == -1 and num[1]!=1) and num[0] == 1:
                    a += f'-x'
                if num[1] > 0 and num[1] != 1 and num [0] == 1 and len(a)>0:
                    a += f'+{num[1]}x'
                if num[1] > 0 and (num[1] == 1 or num[1] == -1) and num [0] == 1 and len(a)>0:
                    a += f'+x'
                if num[1] > 0 and (num[1] == 1 or num[1] == -1) and num [0] == 1 and len(a)==0:
                    a += f'x'
        return a
    # 改为普通命名的degree方法
    def degree(self):
        return max(self.data, key=lambda x:x[0])
    def __str__(self):
        """Return information about polynomial"""
        return self.create_equation()
    def coefficient(self,number):
        the_outcome = 0
        for nuum in self.data:
            if nuum[0] == number:
                the_outcome = nuum[1]
        # 把return放到循环外部
        return the_outcome

# 先实例化对象
poly = Polynomia1([(3, 5), (1, 2), (0, -4)])
# 打印多项式(调用__str__)
print(poly)
# 主动调用degree方法获取最高次
print("最高次项:", poly.degree())
# 主动调用coefficient方法获取指定次数的系数
print("次数为3的系数:", poly.coefficient(3))
print("次数为2的系数:", poly.coefficient(2))

内容的提问来源于stack exchange,提问作者Kokin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 14:36:06