最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Python中继承父类如何重写__init__以自定义初始化

Python crifan 4653浏览 0评论

折腾:

【已解决】pyspider中出错:TypeError __init__() got an unexpected keyword argument resultdb

期间,需要去pyspider中,继承ResultWorker,然后要自定义初始化__init__

用:

<code>class AutohomeResultWorker(ResultWorker):
    mysqldb = None

    def __init__(self, resultdb, inqueue):
        """init mysql db"""
        print("AutohomeResultWorker init")
        print("resultdb=%s, inqueue=%s" % (resultdb, inqueue))
        #super.__init__(self, resultdb, inqueue)
        super.__init__(resultdb, inqueue)

        if self.mysqldb is None:
            self.mysqldb = MysqlDb()
            print("self.mysqldb=%s" % self.mysqldb)
</code>

结果:

    super.__init__(resultdb, inqueue)

TypeError: descriptor ‘__init__’ requires a ‘super’ object but received a ‘ResultDB’

用:

<code>def __init__(self, resultdb, inqueue):
    """init mysql db"""
    print("AutohomeResultWorker init")
    print("resultdb=%s, inqueue=%s" % (resultdb, inqueue))
    super.__init__(self, resultdb, inqueue)
</code>

结果:

    super.__init__(self, resultdb, inqueue)

TypeError: descriptor ‘__init__’ requires a ‘super’ object but received a ‘AutohomeResultWorker’

python override __init__

override – Inheritance and Overriding __init__ in python – Stack Overflow

__init__ method calls overridden method – Python rules – Semmle

<code>class Super(object):
 
    def __init__(self, arg):
        self._state = "Not OK"
        self.super_set_up(arg)
        self._state = "OK"
 
    def super_set_up(self, arg):
        "Do some set up"
 
 
class Sub(Super):
 
    def __init__(self, arg):
        Super.__init__(self, arg)
        self.sub_set_up(self, arg)
        self.important_state = "OK"
 
 
    def sub_set_up(self, arg):
        "Do some more set up"
</code>

Python Tutorial: Inheritance

【总结】

<code>from pyspider.result import ResultWorker

class AutohomeResultWorker(ResultWorker):

    def __init__(self, resultdb, inqueue):
        """init mysql db"""
        print("AutohomeResultWorker init")
        print("resultdb=%s, inqueue=%s" % (resultdb, inqueue))
        ResultWorker.__init__(self, resultdb, inqueue)

        # print("self.mysqldb=%s" % (self.mysqldb))
        # if self.mysqldb is None:
        self.mysqldb = MysqlDb()
        print("self.mysqldb=%s" % self.mysqldb)
</code>

好像就可以实现继承了。

转载请注明:在路上 » 【已解决】Python中继承父类如何重写__init__以自定义初始化

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.191 seconds, using 22.09MB memory