【问题标题】:i m getting "unbound method" error for this code below我收到以下代码的“未绑定方法”错误
【发布时间】:2018-03-20 23:29:28
【问题描述】:
import pandas as pd
class main_class:
    def __init__(self,data_frame):
        self.data_frame = data_frame
    def read_csv(self):
        data_frame = pd.read_csv("outputfile.csv")
        return data_frame
inc = main_class
print(inc.read_csv)

通过运行此代码,我得到了未绑定方法错误

【问题讨论】:

    标签: python-2.7


    【解决方案1】:

    你看到的不是错误,是函数的描述。

    这段代码有几个问题。

    • 您正在打印函数,而不是打印函数的返回值。换句话说,您永远不会调用该函数。

    • 您永远不会创建main_class 的实例。

    解决以上两个问题需要添加()

    inc = main_class()
    #               ^
    print(inc.read_csv())
    #                 ^
    

    现在您将收到 TypeError 错误,因为 main_class.__init__ 需要一个参数。

    • main_class.__init__ 接受一个参数并将其存储到self.data_frame,它不会在任何地方使用。 read_csv 中的 data_frameself.data_frame 无关。

    • 附带说明,Python 2 中的类最好是子类object

      class main_class(object):
          ...
      

    最后,您可能需要阅读 Python 教程,以重新了解类和方法的基本思想是如何工作的。

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 2023-01-23
      • 2011-07-20
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-31
      相关资源
      最近更新 更多