You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行指定Python代码出现unbound method错误,请求排查解决

Unbound Method Error: Cause and Fix

Let's break down what's going wrong with your code and how to fix it, step by step.

First, here's your original code for reference:

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)

Why You're Getting the Unbound Method Error

  • The core problem is you're not instantiating your class. When you write inc = main_class, you're just assigning the class itself to inc—not creating an actual instance of the class. Instance methods like read_csv() need to be bound to a class instance to work properly; accessing them directly via the class gives you an unbound method, which triggers the error.
  • Also, your read_csv() method doesn't actually use the self.data_frame attribute you set in __init__, which is a bit redundant, but let's fix the main error first.

How to Fix It

  1. Properly instantiate the class
    Instead of assigning the class directly, create an instance using parentheses. Since your __init__ expects a data_frame parameter (but your read_csv doesn't use it), you can pass None as a placeholder, or update the __init__ to have a default value for cleaner instantiation:

    # Option 1: Pass a placeholder value
    inc = main_class(None)
    
    # Option 2: Update __init__ with a default parameter
    def __init__(self, data_frame=None):
        self.data_frame = data_frame
    # Then instantiate with just:
    inc = main_class()
    
  2. Call the method (don't just reference it)
    Right now you're printing the method object itself with print(inc.read_csv). To run the method and get the CSV data, add parentheses to call it:

    print(inc.read_csv())
    

Corrected Full Code

Here's the revised code that works as expected:

import pandas as pd

class main_class:
    def __init__(self, data_frame=None):
        self.data_frame = data_frame
    
    def read_csv(self):
        # Optional: If you want to store data in the instance's attribute, use this line instead:
        # self.data_frame = pd.read_csv("outputfile.csv")
        data_frame = pd.read_csv("outputfile.csv")
        return data_frame

# Create an instance of the class
inc = main_class()
# Call the read_csv method and print the result
print(inc.read_csv())

Bonus: Using the Instance Attribute

If your goal was to have the CSV data stored in the class instance for later use, modify the read_csv method to assign to self.data_frame instead of a local variable. That way you can access the data anytime via inc.data_frame after calling the method.

内容的提问来源于stack exchange,提问作者VEERESH NB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:04:54