为什么导入的功能“按原样"另一个名称保留其原始名称______? [英] Why does an imported function "as" another name keep its original __name__?

查看:61
本文介绍了为什么导入的功能“按原样"另一个名称保留其原始名称______?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里:

from os.path import exists as foo
print foo.__name__

我们得到:'exists'. 为什么不'foo'?哪个属性会给出'foo'?

we get: 'exists'. Why not 'foo'? Which attribute would give 'foo'?

推荐答案

您可以将import foo as bar视为一项作业.为该功能分配其他名称时,您不会期望该功能更改其__name__属性.

You can view import foo as bar as just an assignment. You would not expect a function to change its __name__ attribute when you assign another name to the function.

>>> def foo(): pass
>>> 
>>> foo.__name__
'foo'
>>> bar = foo
>>> bar.__name__
'foo'

谢谢.变量bar的哪个属性将返回字符串'bar'?

Thanks. What attribute of the variable bar would return the string 'bar' then?

没有这样的属性.名称(bar)单向引用值(函数对象).

There is no such attribute. Names (bar) refer to values (the function object) unidirectionally.

将函数的__name__属性设置为使用
定义函数的名称 def ...语法.这就是为什么如果定义匿名函数并在创建名称后为其分配名称的原因,那么您就没有有意义的__name__属性的原因.

The __name__ attribute of a function is set as the name the function was defined with using the
def ... syntax. That's why you don't get a meaningful __name__ attribute if you define an anonymous function and assign the name foo after it has been created.

>>> foo = lambda: None
>>> foo.__name__
'<lambda>'

这篇关于为什么导入的功能“按原样"另一个名称保留其原始名称______?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆