简体   繁体   English

双链表的大小

[英]Size of Doubly linked list

I have various functions created and one of them should append data and the size function should be updated after an item is appended. 我创建了各种函数,并且其中之一应附加数据,并且在附加项目后应更新size函数。 however when i do it, i get an error saying unsupported operand type(s) for +: 'method' and 'int . 但是,当我这样做时,我得到一个错误,指出+不支持的操作数类型:'method'和'int。 I'm a little confused to what that means. 我对这意味着什么有些困惑。

def size(self):
    self.length = 0
    return self.length 

def append(self, data):
    new_node = Double_Node(data)
    self.size = self.size + 1
def size(self):
    …

This defines a member size of the class which is a method. 这定义了作为方法的类的成员size So when you try to do self.size + 1 you are trying to add 1 to a method, which is exactly what the error is telling you. 因此,当您尝试执行self.size + 1您尝试将1加到方法中,这正是错误告诉您的内容。

Furthermore, you are also about to assign that result to self.size , essentially overwriting the method, so that's not what you want to do either. 此外,您还将要将该结果分配给self.size ,本质self.size覆盖该方法,因此也不是您想要执行的操作。

Instead, you probably want to increment self.length by one. 相反,您可能希望将self.length增加一。

Note that it is recommended to implement the special method __len__ to allow people to use the len() function with your object which is the standard way to get the length of an object. 请注意,建议实现特殊的方法__len__以允许人们对您的对象使用len()函数,这是获取对象长度的标准方法。 For example: 例如:

def __len__ (self):
    return self.length

In you example, size is a method, not an integer. 在您的示例中, size是一种方法,而不是整数。 You probably mean to call it, but since it's not a property, you'll need to use the property decorator and its setter: 您可能打算调用它,但是由于它不是属性,因此您需要使用属性装饰器及其设置器:

class MyObj(object):
    def __init__(self):
        self.length = 0
    @property
    def size(self):
        return self.length 

    @size.setter
    def size(self, value):
        self.length = value

    def append(self, data):
        self.size = self.size + 1

And then: 接着:

>>> myobj = MyObj()
>>> myobj.length
0
>>> myobj.size
0
>>> myobj.append('foo')
>>> myobj.size
1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM