类型错误:在 Python 2 中必须使用实例作为第一个参数调用未绑定的方法(取而代之的是 int 实例) [英] TypeError: unbound method must be called with instance as first argument (got int instance instead) in Python 2

查看:173
本文介绍了类型错误:在 Python 2 中必须使用实例作为第一个参数调用未绑定的方法(取而代之的是 int 实例)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 python 3 中,以下代码集有效,我想知道为什么在 python 2.7 中它给我一个 TypeError: unbound method add() must be called with calc instance as first argument( got int instance instead)?我如何在 Python 2.7 中解决这个问题?

In python 3 the following set of codes works, I wonder why in python 2.7 it gives me a TypeError: unbound method add() must be called with calc instance as first argument(got int instance instead)? how do I resolve this in Python 2.7?

class calc:
    def add(x,y):
        answer = x + y
        print(answer)

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

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

    def div(x,y):
        answer = x / y
        print(answer)

calc.add(5, 7)

推荐答案

在你的情况下使用 staticmethod for python2.7

Use staticmethod for python2.7 in your case

class calc:

    @staticmethod
    def add(x,y):
        answer = x + y
        print(answer)

#call staticmethod add directly 
#without declaring instance and accessing class variables
calc.add(5,7)

或者,如果您需要调用其他实例方法或使用类中的任何内容,请使用实例方法

Or, Use instance method if you need to call other instance methods or use anything inside class

class calc:

    def add(self,x,y):
        print(self._add(x,y)) #call another instance method _add
    def _add(self,x,y):
        return x+y

#declare instance
c = calc()
#call instance method add
c.add(5,7) 

另外,如果您需要使用类变量但不声明实例,请使用classmethod

Additionally, Use classmethod if you need to use class variables but without declaring instance

class calc:

    some_val = 1

    @classmethod
    def add_plus_one(cls,x,y):
        answer = x + y + cls.some_val #access class variable
        print(answer)

#call classmethod add_plus_one dircetly
#without declaring instance but accessing class variables
calc.add_plus_one(5,7)

这篇关于类型错误:在 Python 2 中必须使用实例作为第一个参数调用未绑定的方法(取而代之的是 int 实例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆