静态函数中的数据框 none

dataframe none inside static function

所以我是 python 的新手,在静态方法中初始化数据框时遇到了问题。这是我的代码:

class class1:
     df = pd.DataFrame()

     @staticmethod
     def static_method_1(df):
          class1.df = returns_a_df()
          print(class1.df)

     @staticmethod
     def static_method_2():
          print(class1.df)               // Here, I get it as none

我使用以下方式调用它:

class1.static_method_1(data)               // data is not empty here
class1.static_method_2()    

         // I get here that df is empty     

因为我在 static_method_1 中初始化 class1.df,为什么它在 static_method_2 中显示为空?我可以在 static_method_1 中打印它,但不能在另一个函数中 感谢任何帮助。

您可以使用 class 变量和函数来实现:

class class1:
 
 def __init__(self):
      self.df = pd.DataFrame()

 def static_method_1(self,df):
      self.df = returns_a_df()
      print(self.df)

 def static_method_2(self):
      print(self.df) 

并调用 class 使用:

w = class1()

或者去掉init中的returns_a_df单独调用:

data = returns_a_df()
w = class1(data)