简体   繁体   中英

Best class structure practice for step by step object manipulation in python

Hi I want to create a class with multiple methods. Each method depends on the result of another method. A simplified example looks like:

class klass(object):
def __init__(self, x, y):
    self.x = x
    self.y = y
    self.results = 0

def method1(self):
    self.results = self.x + self.y
    return self.results

def method2(self):
    self.results = math.sqrt(self.results)
    return self.results

method2 should called only after method1 . ie:

>>> b=klass(3.0, 4.0)
>>> b.method1()
7.0
>>> b.method2()
2.6457513110645907

The idea is that someone may need only the result of method1 and someone else may need the result of method2 as well. So the first person needs to run only method1 and the second person needs to run method1 and then method2 .

What is the best(most readable and simplest) way to do that.

Note that this is a much more simple version of a complex class

I would switch results to be a dictionary and save the results for each level separately. Then you can check in each method if "level1" not in self.results: raise an exception but then you can still provide the output of each level to users. Furthermore you could start each method by checking to see if the results exist already. An example would be like so:

class klass(object):
def __init__(self, x, y):
    self.x = x
    self.y = y
    self.results = {"level0": 0}

def method1(self):
    if "level1" not in self.results:
        self.results["level1"] = self.x + self.y
    return self.results["level1"]

def method2(self):
    if "level1" not in self.results:
        raise ValueError("The results of method1 are not yet available")
    if "level2" not in self.results:
        self.results["level2"] = math.sqrt(self.results["level1"])
    return self.results["level2"]

PS Don't use the name klass

Correct me if I'm getting this wrong, but couldn't you just call method1 in method2 like this:

def method2(self):
    self.method1()
    self.results = math.sqrt(self.results)
    return self.results

You can write separate functions to aggregate functions you need in a single place:

class klass(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.results = 0

    def method1(self):
        self.results = self.x + self.y
        return self.results

    def method2(self):
        self.results = math.sqrt(self.results)
        return self.results

    def both_methods(self):
        self.method1()
        self.method2()
        return self.results

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