Question

I have various functions created and one of them should append data and the size function should be updated after an item is appended. however when i do it, i get an error saying unsupported operand type(s) for +: 'method' and '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
Was it helpful?

Solution

def size(self):
    …

This defines a member size of the class which is a method. 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.

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.

Instead, you probably want to increment self.length by one.

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. For example:

def __len__ (self):
    return self.length

OTHER TIPS

In you example, size is a method, not an integer. 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top