一尘不染

如何使用子类的默认值调用父类的init?

selenium

我试图给我的子类默认变量,并在文件变胖时停止重复代码:

class Base(object):

    def __init__(self, username=None, password=None, start_url=None):
        self.username  = username
        self.password  = password
        self.start_url = start_url

class Subclass(Base):

    def __init__(self, username="hoss_it87", password="whatsgoodSO", start_url="www.boss-sauce.com"):
        super(Subclass, self).__init__()

Base当然可以,但是我想Subclass以同样的方式初始化,只是None用真实的字符串覆盖(所有登录样式都是相似的)。

In [12]: x = Base('myuser', 'mypassword', 'www.google.com')

In [13]: x.username
Out[13]: 'myuser'

In [14]: x.start_url
Out[14]: 'www.google.com'

In [15]: y = Subclass()

In [16]: y.username

In [17]: y.start_url

In [18]: y.password

In [19]:

为什么我什么都没得到Subclass属性,该如何解决?谢谢

请注意,删除基类默认设置会导致其他问题

class Base(object):

    def __init__(self, username, password, start_url):
        self.username  = username
        self.password  = password
        self.start_url = start_url

class Subclass(Base):

    def __init__(self, username="honeybooboosbiggestfan", password="toomuchburkerking", start_url="www.imjokingiprefericeroadtruckers.com"):
        super(Subclass, self).__init__()


In [24]: y = Subclass()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-55b9b4fdf93b> in <module>()
----> 1 y = Subclass()

<ipython-input-23-a9dc62450db7> in __init__(self, username, password, start_url)
      9 
     10     def __init__(self, username="honeybooboosbiggestfan", password="toomuchburkerking", start_url="www.imjokingiprefericeroadtruckers.com"):
---> 11         super(Subclass, self).__init__()

TypeError: __init__() takes exactly 4 arguments (1 given)

In [25]:

解决了:

class Base(object):

    def __init__(self, username, password, start_url):
        self.username  = username
        self.password  = password
        self.start_url = start_url

class Subclass(Base):

    def __init__(self, username="honeybooboosbiggestfan", password="toomuchburkerking", start_url="www.imjokingiprefericeroadtruckers.com"):
        super(Subclass, self).__init__(username=username, password=password, start_url=start_url)

## -- End pasted text --

In [26]: y = Subclass()

In [27]: y.username
Out[27]: 'honeybooboosbiggestfan'

In [28]:

阅读 305

收藏
2020-06-26

共1个答案

一尘不染

您必须将参数从SubClassinit 传递到以下内容的init块Base

class Subclass(Base):

    def __init__(self, username="hoss_it87", password="whatsgoodSO", start_url="www.boss-sauce.com"):
        super(Subclass, self).__init__(username=username, password=password, start_url=start_url)

在您的代码中,Base调用init时不带参数,因此采用其默认参数all None

2020-06-26