简体   繁体   English

从 function 返回多个 obj 的最佳方法

[英]Best approach to return multiple objs from function

Lets say i have 2 classes, i want to take from class First two dfs, to second class, should I return them and unpack or use sefl.df and do not use return if i want to use those dfs in more than one function in other class?假设我有 2 个类,我想从 class 前两个 dfs 到第二个 class,我应该返回它们并解压或使用 sefl.df,如果我想在多个 ZA385C4252748E78 中使用这些 dfs,请不要使用返回其他 class?

I can unpack but its only one per program runs and i cannot unpack two times same function.我可以解包,但每个程序运行只有一个,我不能解包两次相同的 function。

Import pandas as pd

class First:
  def func(self):
    Df = df.read_csv('my data.csv')
    Df2= Df.copy()

    return Df,Df2

class Second(First):
   def one(self):
      Df,Df2 = self.func()
      DF1=....

   def two(self):
      Df,Df2 = self.func()
      Df2=....

The "best" approach really depends on what you are trying to achieve and what restrictions you are dealing with ( and usually has a significant subjective component ). “最佳”方法实际上取决于您要达到的目标以及您要处理的限制(并且通常具有重要的主观成分)。
It doesn't seem to be clear whether flexibility or efficiency is more important from the information you have given, so here is how I would handle such a situation.从您提供的信息来看,似乎并不清楚灵活性还是效率更重要,所以这就是我将如何处理这种情况。

Considering efficiency, my main concern was that every time you call func, you re-read the csv file.考虑到效率,我主要担心的是每次调用 func 时,都会重新读取 csv 文件。 From my experience this is rarely necessary, but if you want it as an option, I would do it like this:根据我的经验,这很少有必要,但如果你想要它作为一个选项,我会这样做:

import pandas as pd

class First:
    def __init__(self, read_now= True):
        if read_now:
            self.Df, self.Df2 = self.func()

    def func(self):
        Df = pd.read_csv('my data.csv')
        Df2= Df.copy()

        return Df,Df2

class Second(First):

    def one(self, reread= False):
        if reread: 
            Df,Df2 = self.func()
        else: 
            Df, Df2 = self.Df, self.Df2
        # operation

    def two(self, reread= False):
        if reread: 
            Df, Df2 = self.func()
        else: 
            Df, Df2 = self.Df, self.Df2
        # operation

By not rereading everytime, you can make it more efficient and modify the dataframe in memory, but you still have the option of easily rereading the dfs if you really need to.通过不每次都重新读取,您可以提高效率并修改 memory 中的 dataframe,但如果您确实需要,您仍然可以轻松地重新读取 dfs。

But as I said, "best" tends to be ambiguous, especially with limited information.但正如我所说,“最佳”往往是模棱两可的,尤其是在信息有限的情况下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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