Python类定义后运行报AttributeError:对象无对应属性问题咨询
Hey there, the root cause of your AttributeError is straightforward: the show() method is trying to access self.pastDataLen and self.recentDataLen, but these two attributes aren't defined anywhere in the __init__ method of your ProjectVarible class. Python throws this error because when you call show() on an instance of the class, it can't find those two properties attached to the object.
How to Fix It
You have two reliable ways to resolve this:
Define the attributes in
__init__(Recommended)
The best practice is to initialize all attributes your class will use in the constructor method. This ensures they exist as soon as the object is created. Just add the missing attribute definitions to__init__, setting default values that make sense for your project:import os import pandas as pd class ProjectVarible: def __init__(self): self.cwd = os.getcwd() self.InPath = self.cwd + '\\data\\' self.OutPath = self.cwd + '\\result\\' self.ipoPreQuarter = 11 self.screenDataPre = 19 self.assetPoolName = 'AllAStock' self.indicator = 'amt' # Add the missing attributes with appropriate default values self.pastDataLen = 10 # Adjust this to your actual required value self.recentDataLen = 5 # Adjust this to your actual required value def show(self): print('current set:') print('pastDataLen = ', self.pastDataLen, end='; ') print('recentDataLen = ', self.recentDataLen, end='; ') # You can add prints for other attributes here too if neededDynamically assign attributes before calling
show()
If these values depend on logic that runs after object creation, make sure you explicitly assign them to the instance before callingshow(). For example:proj_vars = ProjectVarible() # Assign values to the missing attributes first proj_vars.pastDataLen = 15 proj_vars.recentDataLen = 7 # Now call show() without errors proj_vars.show()That said, this approach is less predictable than initializing in
__init__, since you have to remember to set these values every time you create an instance.
Once you implement either fix, the AttributeError should disappear, and your show() method will be able to print the values correctly.
内容的提问来源于stack exchange,提问作者yogazining

