【问题标题】:nameerror: name 'repeatedsubtraction' is not defined名称错误:名称“重复减法”未定义
【发布时间】:2021-07-11 12:35:42
【问题描述】:
import math

class Solution:
    def repeatedSubtraction(self,a,b):

        if a%b == 0:
            return math.floor(a/b)
        return math.floor((a/b)+ repeatedSubtraction(b,a%b))

obj=Solution()
print(obj.repeatedSubtraction(7,2))

【问题讨论】:

  • 添加selfreturn math.floor((a/b)+ self.repeatedSubtraction(b,a%b))

标签: python function class object nameerror


【解决方案1】:

在函数中,您应该使用 self 前缀调用它,如下所示:

return math.floor(a / b + self.repeatedSubtraction(b, a % b))

【讨论】:

    【解决方案2】:

    错误就在这个语句中。

    return math.floor((a/b)+ repeatedSubtraction(b,a%b))
    

    当你在同一个类中调用一个类的函数时 class: 函数名要以self为前缀

    return math.floor((a/b)+ self.repeatedSubtraction(b,a%b))
    

    【讨论】:

      【解决方案3】:
      import math
      
      class Solution:
          def repeatedSubtraction(self,a,b):
      
              if a%b == 0:
                  return math.floor(a/b)
              return math.floor((a/b)+ Solution.repeatedSubtraction(self, b,a%b))
      
      obj=Solution()
      print(obj.repeatedSubtraction(7,2))
      

      【讨论】:

        猜你喜欢
        • 2016-04-30
        • 2022-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-02
        • 2019-06-13
        • 2015-01-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多