内置类属性__name__在Python中做什么?

此内置属性可打印类,类型,函数,方法,描述符或生成器实例的名称。

例如,如果python解释器将该模块(源文件)作为主程序运行,则它将特殊的__name__变量设置为具有值“ __main__”。如果从另一个模块导入该文件,则将__name__设置为模块的名称。

示例

以下代码说明了__name__的用法。

class Bar(object):
    def foo():

       """ This is an example of how a doc_string looks like.

          This string gives useful information about the function being defined.

            """

    pass

    print foo.__name__
print Bar.__name__

输出结果

这给出了输出

foo
Bar