What is a nicer alternative to a namedtuples _replace?

白昼怎懂夜的黑 提交于 2020-01-02 02:28:07

问题


Take this code:

>>> import urlparse
>>> parts = urlparse.urlparse('http://docs.python.org/library/')
>>> parts = parts._replace(path='/3.0'+parts.path)

parts._replace works but as it is an underscored method, it's supposed to be internal, and not used. Is there an alternative? I don't want to do:

>>> parts = parts[:2] + ('/3.0'+parts.path,) + parts[3:]

Because that makes it an ordinary tuple, and not a namedtuple, and doing:

>>> parts = namedtuple(scheme=parts.scheme, netloc=parts.netloc, etc etc)

is kinda stupid. :)

Ideas?


回答1:


The reason methods of namedtuple start with an initial underscore is only to prevent name collisions. They should not be considered to be for internal use only:

To prevent conflicts with field names, the method and attribute names start with an underscore.



来源:https://stackoverflow.com/questions/2213102/what-is-a-nicer-alternative-to-a-namedtuples-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!