Python自定义ArgParse类访问参数提示属性不存在问题求助
问题原因
你定义的CustomArguments类中,parser、arguments都是__init__方法内的局部变量,方法执行完成后就会被回收,不会绑定到类实例上,所以无法通过实例访问这些变量,更无法直接获取locations_file这类参数属性。
解决方案
提供两种常用实现方式,可根据使用习惯选择:
方案1:直接将参数属性绑定到实例(调用方式无需修改)
通过__dict__.update把解析得到的所有参数属性直接挂载到类实例上,完全匹配你现有调用逻辑,无需修改主文件代码。
修改后的类实现:
import argparse class CustomArguments: def __init__(self): parser = argparse.ArgumentParser(description="Possible command line arguments") # 必选参数 parser.add_argument("locations_file", help="POI file location", type=str) parser.add_argument("users_file", help="User file location", type=str) # 可选参数 parser.add_argument("--split", "-s" , help="Split threshold. File will be split if records exceed this amount", type=int, required=False, default=100000) parser.add_argument("--batch_size", "-b" , help="Size for each split of the file.", type=int, required=False, default=100000) parser.add_argument("--max_threads", "-t", help="Max amount of threads for the thread pool", type=int, required=False, default=10) # 核心修改:把解析后的所有参数属性绑定到当前实例 self.__dict__.update(vars(parser.parse_args()))
主文件调用逻辑保持不变即可:
import os app_args = CustomArguments() poi_file = os.path.join(app_args.locations_file)
方案2:将解析结果存为实例属性
如果需要保留完整的解析结果对象,可以把参数存为实例的一个公开属性,调用时通过该属性访问参数。
修改后的类实现:
import argparse class CustomArguments: def __init__(self): # 把parser也绑定到实例,后续需要调整参数配置时可直接调用 self.parser = argparse.ArgumentParser(description="Possible command line arguments") # 必选参数 self.parser.add_argument("locations_file", help="POI file location", type=str) self.parser.add_argument("users_file", help="User file location", type=str) # 可选参数 self.parser.add_argument("--split", "-s" , help="Split threshold. File will be split if records exceed this amount", type=int, required=False, default=100000) self.parser.add_argument("--batch_size", "-b" , help="Size for each split of the file.", type=int, required=False, default=100000) self.parser.add_argument("--max_threads", "-t", help="Max amount of threads for the thread pool", type=int, required=False, default=10) # 把解析结果存为实例属性 self.arguments = self.parser.parse_args()
主文件调用逻辑调整为:
import os app_args = CustomArguments() poi_file = os.path.join(app_args.arguments.locations_file)
内容的提问来源于stack exchange,提问作者Dasph
相关产品推荐
相关产品推荐

