简体   繁体   中英

Return self in python class just returns NoneType

I create a linked list in python and want to build a function to find the last item, but when I design as following, the function returns "None" type. There must be something wrong with "return self" because I print "self" before return it looks fine.

class LinkNode():
    def __init__(self,value=0,next=None):
        self.val=value
        self.next=next
    
    def findlast(self):
        if self.next == None:
            return self
        else:
            self.next.findlast()

The following is to create instances

node3=LinkNode(3,None)
node2=LinkNode(2,node3)
chain=LinkNode(1,node2)
x=chain.findlast()
type(x)

NoneType

def findlast(self):
    if self.next == None:
        return self
    else:
        self.next.findlast()

That last line is a problem since it doesn't return anything from the function, which is why you get None . You should use (also without the superfluous else , and using is with None ):

def findlast(self):
    if self.next is None:
        return self
    return self.next.findlast()

However, just keep in mind this is not the ideal use case for recursion, it may be better written as:

def findlast(obj):
    if obj is not None: # only needed if you may pass in None as self.
        while obj.next is not None:
            obj = obj.next
    return obj

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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