Python 模块属性:名称、文档、文件、字典
2023-09-17 22:16:36
Python 模块有其描述它的属性。属性执行某些任务或包含有关模块的一些信息。 下面介绍了一些重要属性:
__name__属性(__name__ Attribute)
__name__
属性返回模块的名称。默认情况下,文件的名称(不包括扩展名 .py)的值为 __name__attribute。
import math
print(math.__name__) #'math'
同样,它给出了自定义模块的名称,例如 calc 模块将返回"calc"。
import calc
print(calc.__name__) #'calc'
但是,可以通过为此属性分配不同的字符串来修改此操作。更改hello.py
如下所示。
def SayHello(name):
print ("Hi {}! How are you?".format(name))
__name__="SayHello"
并立即检查__name__
属性。
import hello
print(hello.__name__) #'SayHello'
__name__
属性的值在Python interactive shell和main.py
模块中__main__
。
print(__name__)
当我们运行任何 Python 脚本(即模块)时,它的 __name__
属性也设置为 __main__
.
例如,在 IDLE 中创建以下 welcome.py。
print("__name__ = ", __name__)
按 F5 在空闲状态下运行上述 welcome.py。您将看到以下结果。
注意:
__name__ = __main__
但是,导入此模块时,其__name__
设置为其文件名。
现在,在新文件 test.py 中导入欢迎模块,其中包含以下内容。
import welcome
print("__name__ = ", __name__)
现在按 F5 在 IDLE 中运行 test.py。__name__
属性现在是"欢迎"。
__name__ = welcome
此属性允许将 Python 脚本用作可执行文件或模块。
访问__main__ in Python了解更多信息。
__doc__属性(__doc__ Attribute)
__doc__属性表示在模块代码中编写的文档字符串(文档字符串)行。
import math
print(math.__doc__)
请考虑将以下脚本另存为greet.py
模块。
"""This is docstring of test module"""
def SayHello(name):
print ("Hi {}! How are you?".format(name))
return
__doc__
属性将返回在模块代码开头定义的字符串。
import greet
print(greet.__doc__)
__file__属性(__file__ Attribute)
__file__
是一个可选属性,用于保存从中加载它的模块文件的名称和路径。
import io
print(io.__file__) #output: 'C:python37libio.py'
__dict__属性(__dict__ Attribute)
__dict__
属性将返回模块属性、函数和其他定义及其各自值的字典对象。
import math
print(math.__dict__)
dir()是一个内置函数,它还返回模块中所有属性和函数的列表。
import math
print(dir("math"))
您也可以在 IDLE 中使用 dir()
函数,如下所示。
了解有关module attributes in Python Docs的更多信息。
本文内容总结: