调用未绑定方法时出现TypeError,但类\u未定义该方法

2024-09-22 16:40:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我在调用方法时遇到了一个错误,但是调用该方法的对象确实定义了该方法。在

以下是调用方法的位置:

def interpreter(self, ast, expression, stack) # method in Parser.py file
    ...
    elif isinstance(ast, ReadNode):
            self.interpret(ast.location, environment, stack)
            loc = stack.pop()
            input = sys.stdin.read()
            try:
                num = int(input)
            except:
                sys.stderr.write("error: not an integer")
            loc.set(num)
    ...

我在loc.set(num)上得到一个错误

^{pr2}$

下面是IntegerBox类:

from Box import Box

class IntegerBox(Box):

    def __init__(self, value=0):
        self.value = value

    def get(self):
        return self.value

    def set(self, value):
        self.value = value

当我通过调试器检查loc的类型时,它是一个IntegerBox实例。为什么它认为loc不是IntegerBox实例?在


Tags: 实例方法selfboxinputvaluestackdef
1条回答
网友
1楼 · 发布于 2024-09-22 16:40:48

loc不是IntegerBox的实例,而是IntegerBox类。在

例如:

>>> class C(object):
...     def m(self):
...         pass
... 
>>> C.m()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method m() must be called with C instance as first argument (got nothing instead)

但是:

^{pr2}$

您需要检查正在放入堆栈对象的内容。在

编辑:解释未绑定方法

当对实例调用方法时,该实例作为第一个参数隐式传递-这是方法签名中的self参数。如果对类而不是实例调用该方法,则必须显式传递实例,否则将引发未绑定方法的TypeError,因为该方法未“绑定”到该类的特定实例。在

所以: C.m()引发TypeError

C().m()正常

C.m(C())也可以!在

相关问题 更多 >