【问题标题】:Unbound method error in my code我的代码中的未绑定方法错误
【发布时间】:2023-03-09 16:58:01
【问题描述】:
Class test:

    a=10
    b=20
    Def c(self,a,b):
        Return a+b
Print test.a
#10
Print test.b
#20
Print test.c(1,2)

#Error unbound method c()

请指出我是不是错了,我在使用类方面是初学者

对不起,我的代码中的大写字母。我不得不在我的小手机屏幕上输入它。

【问题讨论】:

  • 您拼错了 classdefprintreturn。你标记了 Python 2.7 和 Python 3.x。是哪个?
  • 您需要创建一个新的test 实例才能在其上使用方法。
  • 肯定不是 Python 3
  • 有趣的是,您遇到了一个未绑定的方法错误,而不仅仅是一个类型错误,通知您传入了错误数量的参数。
  • @smarx。确实如此,但您也可以调用类上的方法并为 self 传递显式引用。

标签: python-2.7 python-2.x


【解决方案1】:

你曾尝试直接访问类内的方法。

在类中调用方法需要创建类的实例

以下编程将起作用

class Test:
    a = 10    # class variable
    b = 20    # class variable
    def c(self,a,b):
            return a+b

print Test.a
print Test.b
obj = Test()
print obj.c(1,2) #3

【讨论】:

    【解决方案2】:
    # class is lowercase
    # class names are by convention uppercase (Test)
    class Test:
        # def is lowercase
        def c(self, a, b):
            # return is lowercase
            return a + b
    
    # Create a new instance of the Test class
    test = Test()
    
    print test.c(1, 2)  # prints 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-06
      • 1970-01-01
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      相关资源
      最近更新 更多