[英]python int object is not callable?
Relatively new to Python
. 对
Python
相对较新。 I'm trying to practice linked list but I'm stuck with an error and couldn't figure out what the issue is. 我正在尝试练习链表,但遇到了一个错误 ,无法弄清问题所在。
The error: 错误:
self.assertEqual(l.size(), 1)
TypeError: 'int' object is not callable
The code: 编码:
from node import Node
class List:
def __init__(self):
self.head = None
self.size = 0
def add(self, item):
temp = Node(item)
temp.setNext(self.head) # ERROR ON THIS LINE
self.head = temp
size += 1
def size(self):
return self.size
...
Node: 节点:
class Node:
def __init__(self, data):
self.data = data
self.next = None
....
Test: 测试:
import unittest
import unorderedlist
class TestUnorderedList(unittest.TestCase):
def test_add(self):
l = unorderedlist.List()
l.add(8)
self.assertEqual(l.size(), 1)
if __name__ == '__main__':
unittest.main()
It's funny because if I rename the size()
to len and call it like l.len()
it works fine. 这很有趣,因为如果我将
size()
重命名为len并像l.len()
一样调用它,它将很好地工作。 Anyone have a clue? 有人知道吗?
随着self.size = 0
您隐藏了self.size = 0
size
,因此size
是一个int而不是一个方法。
You have hidden your method with the attribute. 您已使用属性隐藏了方法。 In your code you are then accessing the attribute which is of type
int
and so not callable. 然后,在您的代码中访问
int
类型的属性,因此不可调用。 Avoid to name methods and attributes the same. 避免命名方法和属性相同。
In case you want to achieve properties. 如果您想获得属性。 There is the
@property
decorator: 有
@property
装饰器:
@property
def size(self):
return self._size
In your constructor you just define self._size
and work internally with it. 在构造函数中,您只需定义
self._size
并在内部使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.