【发布时间】:2016-06-27 14:09:10
【问题描述】:
我确实尝试在 Python 2.7 中使用继承并创建第二个类,该类将使用 super 方法和 @classmethod 装饰器来初始化基类。但是,即使将*args 和**kwargs 参数添加到初始化基类的函数中,我仍然无法使其工作。
import socket
class Server(object):
def __init__(self, ip_address, host):
self.ip_address = ip_address
self.host = host
@classmethod
def create_with_host(cls, host, *args, **kwargs):
ip_address = socket.gethostbyname(host)
return cls(ip_address, host, *args, **kwargs)
class WebServer(Server):
def __init__(self, url):
super(WebServer, self).create_with_host(url.split('/')[2])
self.url = url
if __name__ == '__main__':
s1 = Server.create_with_host('www.google.com')
print(s1.host, s1.ip_address)
w1 = WebServer('http://app.pluralsight.com')
print(w1.host, w1.ip_address, w1.url)
错误是:
Traceback (most recent call last):
File "/Users/poc.py", line 26, in <module>
w1 = WebServer('http://app.pluralsight.com')
File "/Users/poc.py", line 19, in __init__
super(WebServer, self).create_with_host(url.split('/')[2])
File "/Users/poc.py", line 13, in create_with_host
return cls(ip_address, host, *args, **kwargs)
TypeError: __init__() takes exactly 2 arguments (3 given)
【问题讨论】:
标签: python python-2.7 inheritance super python-decorators