我试图给我的子类默认变量并在文件变胖时停止复制代码:
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]:
答案 0 :(得分:4)
您必须将SubClass
init中的参数传递给Base
的init块:
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在没有参数的情况下被调用,因此采用其默认参数,这些参数都是None
。