【问题标题】:TypeError: unbound method mult() must be called with calculadora instance as first argument (got int instance instead)类型错误:必须使用 calculadora 实例作为第一个参数调用未绑定的方法 mult()(改为获取 int 实例)
【发布时间】:2017-04-03 00:54:18
【问题描述】:

我得到一个 TypeError: unbound method mult() must be called with calculadora instance 作为第一个参数(取而代之的是 int 实例)

运行我的 python 文件时:

    from __future__ import print_function

class calculadora:


    def suma(x,y):
        added = x + y
        print(added)

    def resta(x,y):
        sub = x - y
        print(sub)

    def mult(x,y):
        multi = x * y
        print(multi)


calculadora.mult(3,5)

【问题讨论】:

  • 您是打算在这里尝试创建静态方法,还是要实例方法?
  • @idjaw 我想要实例方法

标签: python python-2.7


【解决方案1】:

如果你想以静态方法访问方法(访问方法没有 clas 实例),你需要用@staticmethod装饰它们:

class calculadora:
    @staticmethod
    def suma(x, y):
        added = x + y
        print(added)

    @staticmethod
    def resta(x, y):
        sub = x - y
        print(sub)

    @staticmethod
    def mult(x, y):
        multi = x * y
        print(multi)

如果您指的是实例方法,则需要先创建实例。并且需要修改方法的签名以包含self作为第一个参数:

class calculadora:
    def suma(self, x, y): # not `self`, refering class instance
        added = x + y
        print(added)

    def resta(self, x, y):
        sub = x - y
        print(sub)

    def mult(self, x, y):
        multi = x * y
        print(multi)


c = calculadora()  # Create instance
c.mult(3,5)  # Access the method through instance, (not class)

【讨论】:

  • 我们不确定。如果他们实际上想要静态方法或实例方法,最好得到澄清。
  • @idjaw,代码没有指定self.,根本没有使用实例变量。 OP也没有创建任何实例;所以我认为这都是静态方法。无论如何,我也会添加实例方法版本。
  • 确实如此。老实说,它可以去任何一种方式:P
  • 是的,我试图做一些我在博客上读到的事情,但他的代码就像我在问题上写的一样。但我使用的是 python 2.7,本教程使用的是 python 3.x
  • @FidelCastro 如果你使用的是Python2.7,最好使用新的样式类:python.org/doc/newstyle
猜你喜欢
  • 2013-12-31
  • 2017-05-10
  • 1970-01-01
  • 2017-04-03
  • 2011-05-27
  • 2018-02-18
  • 2023-04-06
  • 1970-01-01
  • 2017-11-30
相关资源
最近更新 更多