Python如何将父类方法中的变量传递给子类方法?
问题原因分析
你的运行结果和预期不符不是单一继承逻辑问题,是多处代码错误共同导致的:
- 核心流程缺陷:父类
openWordlist方法仅将遍历到的单词赋值给self.word属性,没有在每拿到一个单词时触发子类的scanDomain方法,遍历结束后self.word只会保留字典最后一行的内容。如果你的字典最后一行是空行,strip处理后self.word就是空字符串,拼接后自然只能得到https://google.com/的结果。 - 调用逻辑错误:你实例化的子类对象名为
d,后续却使用未定义的directoryScan变量调用方法,同时没有给self.wordlistFile赋值实际的字典文件路径,运行时会直接抛出异常。 - 语法&依赖缺失:未导入
requests库和对应的InvalidURL异常类,第一处打印的格式化字符串没有加f前缀,代码中用到的self.targetURL没有提前定义,都会触发运行报错。
修正后的代码
调整父类方法逻辑,每读取到一个单词就主动调用scanDomain方法,补全所有缺失的依赖、变量赋值和语法问题,最终代码如下:
import requests from requests.exceptions import InvalidURL class Main: def __init__(self): self.wordlistFile = '' self.word = '' def openWordlist(self): with open(self.wordlistFile, 'r', encoding='utf-8') as suppliedWordlist: for word in suppliedWordlist: word = word.strip() if not word: # 跳过空行 continue self.word = word self.scanDomain() # 每拿到一个单词就调用扫描方法 class DirectoryScan(Main): def scanDomain(self): try: self.cleanURL = 'https://google.com' + self.word self.reqURL = requests.get(self.cleanURL, timeout=5) # 加超时避免长时间卡住 if self.reqURL.status_code == 200: print(f'Found: {self.cleanURL}') except InvalidURL: print(f'{self.cleanURL} 不是有效的URL') except Exception as e: # 捕获其他异常避免程序直接崩溃 pass if __name__ == '__main__': d = DirectoryScan() d.wordlistFile = 'wordlist.txt' # 替换为你实际的字典文件路径 d.openWordlist()
内容的提问来源于stack exchange,提问作者sunflower
相关产品推荐
相关产品推荐

