首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

各位帮个忙,关于Python的下划线加括号的有关问题

2012-05-31 
各位帮个忙,关于Python的下划线加括号的问题经常关注python的开源工程,发现其中好多的类有如下的写法:Pyth

各位帮个忙,关于Python的下划线加括号的问题
经常关注python的开源工程,发现其中好多的类有如下的写法:

Python code
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() 
直接运行该程序,出现NameError: name '_' is not defined的错误。
请问message = _("An unknown exception occurred.")表示什么意思?
类似的下划线加括号的到底应该如何使用?

谢谢各位!

[解决办法]
Python code
def _(str):    print str    _("Hello world!")
[解决办法]
探讨
Python code
def _(str):
print str

_("Hello world!")


是自己定义的类或者方法吧,自己找找

[解决办法]
我也估计是自定义函数,python可以用下划线和双下划线做函数名,还是挺好玩的

Python code
>>> def _(s):    print s    >>> _('s')s>>> def __(s):    print s+s    >>> __('s')ss>>>
[解决办法]
一般是做本地化时,把_定义成一个翻译函数来用,看看gettext模块...
[解决办法]
Python code
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
Python code
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.') 

热点排行