Python新手求助:如何调用其他文件中类的方法?
解决跨文件调用类方法的问题
问题分析与修复步骤:
导入名称不匹配
你的id_1.py中导入的是base_file,但base_file.py里的类实际名为basefile(注意小写的f),修正导入语句:# id_1.py 修正导入 from base_file import basefile实例方法调用方式错误
find_method是带self参数的实例方法,不能直接通过类名调用,必须先创建类的实例:# id_1.py 中修正调用逻辑 class id_1: def condition(self): # 补充self参数,否则无法作为实例方法调用 day_part_response = ...some response... current_time = ...some value... # 创建basefile类的实例 base_instance = basefile() # 通过实例调用方法 abc = base_instance.find_method(x=day_part_response, y=current_time)另外,
base_file.py里的day_response未定义,应该是传入的参数x,需要把循环语句改成for day in x,否则会触发NameError。可选:改为静态方法(无需实例)
如果不需要使用basefile类的实例属性(比如self.start_time),可以把find_method改成静态方法,这样不用创建实例就能调用:# base_file.py 修改为静态方法 class basefile: @staticmethod def find_method(x, y): for day in x: start = day["start_time"] end = day["end_time"] if (condition): day_id = day["_id"] entity_ID = day["entity_id"] restore = True # 若create_entity依赖实例属性,此方法不适用,仍需用实例方法 return start, end, day_id, entity_ID, restore
内容的提问来源于stack exchange,提问作者Ramii
相关产品推荐
相关产品推荐

