我有一个名为EasyUrl()
的类,该类是从urlparse.Parseresult()
派生的。 ParseResult()
在调用urlparse.urlparse(url)
时被实例化,我在EasyUrl()
中有一个静态方法,该方法将实例化的ParseResult()
对象的类类型更改为EasyUrl()
对象。我将urlparse.urlparse()
函数和类类型转换包装到函数parse_url()
中。
该函数背后的原因是,我试图破解一个我不需要答案但想要解决的单独问题,是在实例化过程中调用TypeError
时得到了__new__
知道我的参数数目无效。
直接实例化EasyUrl()
时收到错误
# snippet
url = 'stackoverflow.com'
url = EasyUrl(url)
# snippet end
Output:
TypeError: __new__() takes exactly 7 arguments (2 given)
ParseResult()
类从namedtuple()
继承。摘自urlparse库
class ParseResult(namedtuple('ParseResult', 'scheme netloc path params query fragment'), ResultMixin):
__slots__ = ()
def geturl(self):
return urlunparse(self)
现在,我已经描述了代码的一些功能,这就是问题所在。我无法访问命名元组的(ParseResult)属性。我正在尝试为
ParseResult()
实现默认方案(如果缺少)。但是我无法访问类定义中的属性。
import urlparse
def parse_url(url):
""" Return a parsed EasyUrl() object"""
parse_result = urlparse.urlparse(url)
return EasyUrl.EvolveParseResult(parse_result)
class EasyUrl(urlparse.ParseResult):
@staticmethod
def EvolveParseResult(parse_result):
""" Change the type of class into a EasyUrl() Object."""
parse_result.__class__ = EasyUrl
easy_url = parse_result # For readabilty
easy_url.init()
return easy_url
def __init__(self, url):
self = parse_url(url) # doesn't work
def init(self):
self.url = self.geturl()
#self.set_scheme_if_non() # Uncomment when no error is raised
def set_scheme_if_non(self, scheme='http'):
if not self.scheme:
self.scheme = scheme
self.url = self.geturl() # Rebuild our url with the new scheme
# Passes the set_scheme_if_non trigger
#url = 'https://stackoverflow.com'
# Fails if statment, then attempts to set the variable,
# but error is raised: AttributeError: can't set attribute
url = 'stackoverflow.com'
# Will give the error: TypeError: __new__() takes exactly 7 arguments (2 given)
#url = EasyUrl(url)
# works fine, I don't know why. Except that I can't access
# the tuples attributes in the class definition
url = parse_url(url)
print url.scheme # Works fine
url.set_scheme_if_non() # Raises an error
输出量
File "/home/crispycret/easyurl.py", line 50, in <module>
url.set_scheme_if_non() # Raises an error
File "/home/crispycret/easyurl.py", line 29, in set_scheme_if_non
self.scheme = scheme
AttributeError: can't set attribute
最佳答案
为什么不从头开始创建新类并从ParseResult
转移所有属性呢?
import urlparse
class EasyURL(object):
def __init__(self, parse_result):
self.scheme = parse_result.scheme
self.netloc = parse_result.netloc
self.path = parse_result.path
self.params = parse_result.params
self.query = parse_result.query
self.fragment = parse_result.fragment
@classmethod
def from_url(cls, url):
return cls(urlparse.urlparse(url))
if __name__ == '__main__':
url = 'http://foo.bar.com:8888/path/to/script.php?a=1&b=2'
# Call from_url class method, which is very convenient
easy_url = EasyURL.from_url(url)
# Or, do it yourself
easy_url = EasyURL(urlparse.urlparse(url))
现在,您可以根据需要将任何其他方法添加到此类。
更新资料
namedtuple
是一个可动态创建新类型的函数。顺便说一下,除非我们为EasyURL
添加一些代码,否则我们的__getitem__()
对象将不会充当元组。ParseResult
不允许您更改诸如scheme
之类的属性,因此没有理由继承它。