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

Python类定义后运行报AttributeError:对象无对应属性问题咨询

AttributeError in ProjectVarible Class: Missing Attributes

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:

  1. 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 needed
    
  2. Dynamically 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 calling show(). 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:30:23