操作namedtuple()派生类中的属性

2024-10-04 03:27:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为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()。在

摘自urlparse库

^{pr2}$

现在我已经描述了代码的一些功能,问题就在这里。我无法访问命名元组的(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

Tags: the实例selfurlifparsedeferror
1条回答
网友
1楼 · 发布于 2024-10-04 03:27:47

为什么不从头开始创建一个新类,并将所有属性从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,因此没有理由继承它。在

相关问题 更多 >