我有一个名为EasyUrl()
的类,它是从urlparse.Parseresult()
派生的。ParseResult()
是在调用urlparse.urlparse(url)
时实例化的,我在EasyUrl()
内有一个静态方法,它将实例化的ParseResult()
对象的类类型更改为EasyUrl()
对象。我将urlparse.urlparse()
函数和类类型转换包装成一个函数parse_url()
。在
这样一个函数背后的原因是,我试图解决一个我不需要答案但却想要答案的单独问题,即在实例化过程中调用TypeError
,这让我知道我的参数数目无效。在
EasyUrl()
时收到错误# snippet
url = 'stackoverflow.com'
url = EasyUrl(url)
# snippet end
Output:
TypeError: __new__() takes exactly 7 arguments (2 given)
ParseResult()
类继承自namedtuple()
。在
现在我已经描述了代码的一些功能,问题就在这里。我无法访问命名元组的(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
转移过来呢?在现在可以根据需要向该类添加任何其他方法。在
更新
namedtuple
是一个动态创建新类型的函数。顺便说一句,我们的EasyURL
对象不会充当元组,除非我们为__getitem__()
添加一些代码ParseResult
不允许您更改属性,例如scheme
,因此没有理由继承它。在相关问题 更多 >
编程相关推荐