2

从类中的方法传递返回值的正确方法是什么?你总是在需要的时候调用该方法还是可以将返回的值存储在 init 方法中?假设我有:

class Foo():

    def __init__(self):

    def heavy_method(self):
        #slow crunching
        return crunch

    def use_heavy_crunch(self):
        data = self.heavy_crunch()
        for i in data:
            #do data stuff
            #return data stuff

    def other_func_that_need_heavy_method(self):
        pass

d = Foo()
d.use_heavy_crunch()

我想知道的是上面的结构是正确的方式还是下面的方式是等效的或更好的?

class Foo()

    def __init__(self):
        self.data = None

    def heavy_method(self):
        #slow crunching
        self.data = crunch

    def use_heavy_crunch(self):
        for i in self.data:
            #do data stuff
            #return data stuff

    def other_func_that_need_heavy_method(self):
        pass

d = Foo()
d.heavy_method()
d.use_heavy_crunch()

所以在上面的例子中,一个方法在另一个方法中被调用,而在下面的例子中,方法的返回值被传递给 init 方法中的一个变量,然后在另一个函数中使用。

4

2 回答 2

1

如果我理解正确,您正在尝试做类似的事情

class Foo():

    def __init__(self):
        self.data = self.heavy_method() # we assign the return value to an attribute of our object

    def heavy_method(self):
        #slow crunching
        return crunch

    def use_heavy_crunch(self):
        for i in self.data: # Notice it's now self.data
            #do data stuff
            #return data stuff

    def other_func_that_need_heavy_method(self):
        pass

d = Foo()
d.use_heavy_crunch()
于 2020-03-05T15:34:47.540 回答
1

您不希望类的初始化方法执行繁重的处理任务,这通常是不好的做法,类初始化应该只用于初始化基于类的实例变量。如果您打算d.use_heavy_crunch()在创建实例后多次调用d并且返回值d.heavy_method()没有随时间变化,那么第二种方法是不错的方法,因为每次调用第一种方法时,d.use_heavy_crunch()您都在调用d.heavy_method()和执行重复相同的任务。在第二种方法中,您只会调用d.heavy_method()一次,然后在其他类方法中使用它的结果。

于 2020-03-05T15:46:08.580 回答