Python问题求助:runtest()未通过密码验证即提前执行
问题解决:runtest()在密码验证前提前执行的原因与修复方案
核心问题
你在实例化password_log时写了password_log(main.runtest()),这里的()是方法调用运算符,会立刻执行runtest(),把它的返回值传给password_log,而不是把这个方法本身传过去留到验证通过后再调用。
修复步骤
1. 修改main.py的传参方式
把传参里的括号去掉,传递方法本身:
# main.py里的实例化代码改成这样 pl = password_log(main.runtest) # 去掉runtest后面的()
2. 调整sc.py的password_log类逻辑
让password_log类在密码验证通过后,主动调用传入的方法。示例结构如下:
# sc.py class password_log: def __init__(self, target_method): # 保存传入的方法对象 self.target_method = target_method # 这里可以初始化日志相关属性 def check_password(self): # 密码验证逻辑 user_pwd = input("请输入密码:") if user_pwd == "your_valid_password": # 替换成你的实际验证条件 print("密码验证通过") # 验证通过后执行目标方法 self.target_method() # 这里添加日志记录逻辑 else: print("密码错误,无法执行操作") # 这里添加错误日志记录逻辑
3. 启动验证流程
在main.py里,实例化后调用验证方法触发整个流程:
# main.py class main: @staticmethod def runtest(): print("runtest执行") if __name__ == "__main__": import sc pl = sc.password_log(main.runtest) pl.check_password() # 启动密码验证
原理说明
- 不加括号的
main.runtest是一个方法对象,相当于把这个方法的“引用”传给password_log,而不是立刻执行它 - 只有当密码验证通过后,
password_log里的self.target_method()才会真正调用这个方法,实现你需要的“验证通过后再执行”的逻辑
内容的提问来源于stack exchange,提问作者Von Lopez
相关产品推荐
相关产品推荐

