You need to enable JavaScript to run this app. 编写Python计算x整数次幂的类时报实例化及方法参数错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

编写Python计算x整数次幂的类时报实例化及方法参数错误如何解决

Python类计算幂次的代码问题修复

具体问题原因

  • 第一处报错(power() takes no arguments):你定义的power类没有实现构造方法__init__,Python的类默认使用不带参数的构造方法,所以实例化时传入x和n两个参数会触发报错。
  • 第二处报错(_pow_() missing 2 required positional arguments: 'x' and 'n'):你定义的_pow_方法声明了需要接收x、n两个入参,但是调用obj._pow_()时没有传入对应参数,触发参数缺失报错。
  • 额外隐藏问题:你的代码存在缩进错误,_pow_方法下的代码没有正确缩进,且你导入了math库但完全没有使用,还有自定义方法命名不规范,_xxx_前后单下划线的命名容易和Python魔法方法混淆。

修复方案

方案1:实例化时传入x、n,计算时无需传参

class Power:
    # 构造方法,实例化时接收参数并绑定到实例属性
    def __init__(self, x, n):
        self.x = x
        self.n = n
    
    # 计算幂次的普通方法
    def get_power(self):
        return self.x ** self.n

x = int(input("Enter the value of x: "))
n = int(input("Enter the value of n: "))
obj = Power(x, n)
print(obj.get_power())

方案2:实例化时无需传参,调用计算方法时传入x、n

class Power:
    def get_power(self, x, n):
        return x ** n

x = int(input("Enter the value of x: "))
n = int(input("Enter the value of n: "))
obj = Power()
print(obj.get_power(x, n))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 02:45:03