为什么我不能命名一个函数`next` - ' int'对象不可调用

时间:2018-03-08 03:13:36

标签: python

我创建了一个简单的类,并命名了一个方法next,它在调用时失败。

class Node():
    def __init__(self, val):
        self.val = val
        self.next = 0

    def next(self, obj):
        self.next = obj

执行代码:

a = Node(1)
b = Node(2)
a.next(b)       <-TypeError: 'int' object is not callable

但是,我得到了TypeError: 'int' object is not callablenext以外的任何其他名称都可以正常工作,甚至可以作为&#39;对象&#39; /&#39;范围&#39;没有重现这个问题。

3 个答案:

答案 0 :(得分:4)

你在构造函数中覆盖了next的值:你一个名为next的函数,但用0替换了该函数。

答案 1 :(得分:1)

这很简单!

您已将 next 初始化为整数:

  

self.next = 0

之后,您尝试将其称为功能。只需重命名该功能或成员。

答案 2 :(得分:0)

只需删除self.next = 0,因为你定义了self.next是int类型,你接下来的函数输入obj类型,是错误

In [18]: class Node():
    ...:     def __init__(self, val):
    ...:         self.val = val
    ...:
    ...:     def next(self, obj):
    ...:         self.next = obj
    ...:

In [19]: a = Node(1)

In [20]: b = Node(2)

In [21]: a.next(b)

In [22]: a.next.val
Out[22]: 2