简体   繁体   中英

Recursive call to class method doesn't return value on first call - Python

I have a class with setter/getter methods, but the getter method doesn't return a value on my initial call:

import random

class Data:
    def __init__(self):
        self.data = {}

    def set_value(self, k):
        self.data[k] = random.random()

    def get_value(self, k):
        if self.data.get(k) is not None:
            return self.data.get(k)

        self.set_value(k)
        self.get_value(k)

Now if I initiate this class and call for a value like 4, on first call it assign a value for 4, but doesn't return it eventhou I'm calling it after the setter function:

d = Data()

d.get_value(4) # returns None

d.data # {4: 0.7578261616519488}

d.get_value(4) # returns 0.7578261616519488

You didn't return the value returned by the recursive call.

def get_value(self, k):
    if self.data.get(k) is not None:
        return self.data.get(k)

    self.set_value(k)
     self.get_value(k)

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