为什么一个导入的函数"as"另一个名字保持原来的__name__?
Why does an imported function "as" another name keep its original __name__?
这里:
from os.path import exists as foo
print foo.__name__
我们得到:'exists'
。
为什么不 'foo'
?哪个属性会给出 'foo'
?
您可以将 import foo as bar
视为一项作业。当您为函数指定另一个名称时,您不会期望函数更改其 __name__
属性。
>>> def foo(): pass
>>>
>>> foo.__name__
'foo'
>>> bar = foo
>>> bar.__name__
'foo'
Thanks. What attribute of the variable bar
would return the string 'bar'
then?
没有这样的属性。名称 (bar
) 单向引用值(函数对象)。
函数的 __name__
属性设置为使用
定义函数的名称
def ...
语法。这就是为什么如果您定义匿名函数并在创建后分配名称 foo
,则不会获得有意义的 __name__
属性。
>>> foo = lambda: None
>>> foo.__name__
'<lambda>'
as
是导入的 file/session 中的语法糖,而 __name__
属性是函数对象的一部分。
导入一个对象只是绑定一个新变量,添加as newname
所做的只是让你选择一个替代名称用于当前命名空间中的变量.
对象上的 __name__
属性与它当前绑定的名称无关,毕竟您可以有任意数量的变量以及指向同一对象的列表或字典等容器:
def foo(): pass
bar = foo
spam = foo
list_of_functions = [foo]
dictionary_of_functions = {'monty': foo, 'python': foo}
上面创建了 4 个额外的函数对象引用;您不能让 foo.__name__
反映所有这些,并且 list_of_functions
和 dictionary_of_functions
中的引用没有(直接)名称。
由于 import foo
、import bar as foo
、from module import foo
和 from module import bar as foo
都只是在当前模块中设置了名称 foo
,所以它们的处理方式完全相同方式与其他作业一样。您也可以使用不同的名称多次导入该函数。
相反,函数的 __name__
值设置为它在 def <name>(...):
语句中定义的名称。它最多是一个调试辅助工具。例如,它用于回溯中,以便更容易识别回溯中显示的代码行。如果这有助于更好地识别位置,您只需将 __name__
设置为其他内容。 (注意:在 Python 3 中,还有 __qualname_
attribute,用于代替 __name__
,因为它包含更多关于嵌套或在 [= 上定义函数时在哪里定义函数的信息40=]).
这里:
from os.path import exists as foo
print foo.__name__
我们得到:'exists'
。
为什么不 'foo'
?哪个属性会给出 'foo'
?
您可以将 import foo as bar
视为一项作业。当您为函数指定另一个名称时,您不会期望函数更改其 __name__
属性。
>>> def foo(): pass
>>>
>>> foo.__name__
'foo'
>>> bar = foo
>>> bar.__name__
'foo'
Thanks. What attribute of the variable
bar
would return the string'bar'
then?
没有这样的属性。名称 (bar
) 单向引用值(函数对象)。
函数的 __name__
属性设置为使用
定义函数的名称
def ...
语法。这就是为什么如果您定义匿名函数并在创建后分配名称 foo
,则不会获得有意义的 __name__
属性。
>>> foo = lambda: None
>>> foo.__name__
'<lambda>'
as
是导入的 file/session 中的语法糖,而 __name__
属性是函数对象的一部分。
导入一个对象只是绑定一个新变量,添加as newname
所做的只是让你选择一个替代名称用于当前命名空间中的变量.
对象上的 __name__
属性与它当前绑定的名称无关,毕竟您可以有任意数量的变量以及指向同一对象的列表或字典等容器:
def foo(): pass
bar = foo
spam = foo
list_of_functions = [foo]
dictionary_of_functions = {'monty': foo, 'python': foo}
上面创建了 4 个额外的函数对象引用;您不能让 foo.__name__
反映所有这些,并且 list_of_functions
和 dictionary_of_functions
中的引用没有(直接)名称。
由于 import foo
、import bar as foo
、from module import foo
和 from module import bar as foo
都只是在当前模块中设置了名称 foo
,所以它们的处理方式完全相同方式与其他作业一样。您也可以使用不同的名称多次导入该函数。
相反,函数的 __name__
值设置为它在 def <name>(...):
语句中定义的名称。它最多是一个调试辅助工具。例如,它用于回溯中,以便更容易识别回溯中显示的代码行。如果这有助于更好地识别位置,您只需将 __name__
设置为其他内容。 (注意:在 Python 3 中,还有 __qualname_
attribute,用于代替 __name__
,因为它包含更多关于嵌套或在 [= 上定义函数时在哪里定义函数的信息40=]).