各位帮个忙,关于Python的下划线加括号的问题
经常关注python的开源工程,发现其中好多的类有如下的写法:
class TestException(Exception): [color=#FF0000][b][size=24px]message = _("An unknown exception occurred.")[/size][/b][/color] def __init__(self, **kwargs): self.kwargs = kwargs try: self._error_string = self.message % kwargs except Exception: # at least get the core message out if something happened self._error_string = self.message def __str__(self): return self._error_string if __name__ == "__main__": ex = TestException()
def _(str): print str _("Hello world!")
[解决办法]
>>> def _(s): print s >>> _('s')s>>> def __(s): print s+s >>> __('s')ss>>>
[解决办法]
一般是做本地化时,把_定义成一个翻译函数来用,看看gettext模块...
[解决办法]
Internationalization (i18n) Strings-----------------------------------In order to support multiple languages, we have a mechanism to supportautomatic translations of exception and log strings.Example:: msg = _("An error occurred") raise HTTPBadRequest(explanation=msg)If you have a variable to place within the string, first internationalize thetemplate string then do the replacement.Example:: msg = _("Missing parameter: %s") % ("flavor",) LOG.error(msg)If you have multiple variables to place in the string, use keyword parameters.This helps our translators reorder parameters when needed.Example:: msg = _("The server with id %(s_id)s has no key %(m_key)s") LOG.error(msg % {"s_id": "1234", "m_key": "imageId"})
[解决办法]
gettext module
Here’s an example of typical usage for this API:import gettextgettext.bindtextdomain('myapplication', '/path/to/my/language/directory')gettext.textdomain('myapplication')_ = gettext.gettext# ...print _('This is a translatable string.')