运行指定Python代码出现unbound method错误,请求排查解决
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 toinc—not creating an actual instance of the class. Instance methods likeread_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 theself.data_frameattribute you set in__init__, which is a bit redundant, but let's fix the main error first.
How to Fix It
Properly instantiate the class
Instead of assigning the class directly, create an instance using parentheses. Since your__init__expects adata_frameparameter (but yourread_csvdoesn't use it), you can passNoneas 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()Call the method (don't just reference it)
Right now you're printing the method object itself withprint(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

