简体   繁体   English

您可以在Django中为下划线分配变量吗

[英]Can You Assign Variables to Underscore In Django

It's always struck me a weird that Django uses the underscore as an operator, given that the underscore is normally used to for assignment to variables that you don't want to reference later. Django使用下划线作为运算符总是让我感到奇怪,因为下划线通常用于分配给您以后不想引用的变量。 Eg 例如

_, file_name = os.path.split(file_path)

Does this mean that you can't assign a unwanted variable to _ in the same namespace as you want to use the _("column_name") notation? 这是否意味着您无法在要使用_("column_name")表示法的同一个命名空间中为_分配不需要的变量?

_ is just another name, perfectly valid even though it looks strange. _只是另一个名字,即使看起来很奇怪也完全有效 And just like any other name, rebinding it will make the old reference unavailable. 就像其他任何名称一样,重新绑定它会使旧的引用不可用。

I think you are confusing a _ variable with Django's from django.utils.translation import gettext as _ , the first _ as used by you is a throwaway variable which is commonly used as convention. 我认为您正在将_变量与from django.utils.translation import gettext as _ Django混淆,您使用的第一个_是一次性变量,通常用作约定。 Django also commonly imports gettext as _ to display translated text, for eg: Django通常也将gettext作为_导入以显示翻译后的文本,例如:

from django.http import HttpResponse
from django.utils.translation import gettext as _

def my_view(request):
    output = _("Welcome to my site.")
    return HttpResponse(output)

Also the underscore character (_) is used to represent “the previous result” in Python's interactive shell and doctest tests. 另外,下划线字符(_)用于表示Python的交互式shell和doctest测试中的“先前的结果”。 Installing a global _() function causes interference. 安装全局_()函数会引起干扰。 Explicitly importing gettext() as _() avoids this problem. 明确地将gettext()导入为_()可以避免此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM