Skip to main content
 首页 » 编程设计

python之类继承问题

2025年05月04日13lidabo

我正在尝试创建一个扩展 HTTPBasicAuthHandler 的类。出于某种原因,我在旧代码中使用的相同方法在这里不起作用。

class AuthInfo(urllib2.HTTPBasicAuthHandler): 
    def __init__(self, realm, url, username, password): 
        self.pwdmgr     = urllib2.HTTPPasswordMgrWithDefaultRealm() 
        self.pwdmgr.add_password(None, url, username, password) 
        super(AuthInfo, self).__init__(self.pwdmgr) 

这里是错误:

Traceback (most recent call last): 
  File "./RestResult.py", line 67, in ? 
    auth = AuthInfo(None, "default", "xxxxx", "xxxxxxxx") 
  File "./RestResult.py", line 47, in __init__ 
    super(AuthInfo, self).__init__(self.pwdmgr) 
TypeError: super() argument 1 must be type, not classobj 

请您参考如下方法:

urllib2.HTTPBasicAuthHandler 类是老式类(它不继承自object),这意味着它不能与 一起使用 super 。您必须直接调用它的 __init__:

urllib2.HTTPBasicAuthHandler.__init__(self, self.pwdmgr)