一、__doc__
用于获取对象的文档字符串,文档字符串用三重引号表示,可以在函数、类、模块等Python对象中使用,于描述该对象的用途、参数、返回值等信息。
def my_function(): """This is the docstring for my_function.""" pass print(my_function.__doc__) # Output: This is the docstring for my_function.
二、__name__
__name__的值取决于代码是如何运行的。当我们编写一个Python脚本时,我们可以使用__name__变量来判断代码是被直接运行还是被导入到其他程序中时执行。一个模块被直接运行时,Python会把__name__赋值为__main__,否则__name__的值为模块名。
直接运行时执行:
def main(): print("Hello, world!") if __name__ == "__main__": main()导入时执行:
example.py
def say_hello(): print("Hello, world!") if __name__ == "example": # 直接运行该py时,没有任何显示,因为__name__的值为__main__ say_hello()test.py
import example print(example.__name__) # 导入时__name__为模块名 # 运行结果为: """ Hello, world! example """ #解释:在导入example时会运行example模块里的代码,这时__name__的值为example模块名,执行say_hello()函数
三、__file__
用于获取当前模块的文件路径。在Python中,每个模块都有一个__file__属性,可以通过该属性获取模块所在的文件路径。__file__变量可以用于获取模块所在的目录,或者用于读取模块所在的文件内容。
# test.py print(__file__) #/Users/bangbang/PycharmProjects/pythonProject/test.py # 获取文件目录 import os os.path.dirname(__file__) # 绝对路径 os.path.abspath(__file__) #/Users/bangbang/PycharmProjects/pythonProject/test.py
# 当前文件的绝对路径的目录
os.path.dirname(os.path.abspath(__file__))
# __file__与os.path.abspath(__file__)有什么区别
""" os.path.abspath(__file__)获取的是当前脚本的绝对路径,而__file__获取的是当前脚本的相对或绝对路径。在大多数情况下,这两种方法都可以得到相同的结果。
但是,如果脚本被移动到另一个位置,则__file__可能会得到错误的路径,而os.path.abspath(__file__)则总是可以得到正确的绝对路径。 """
# 读取当前模块内容
with open(__file__,mode='r',encoding="utf-8") as f:
print(f.read())
四、__all__(一般不使用,我们都是导入具体的属性或方法,很少导入整个模块)
用于定义模块中哪些属性、方法和类应该被导出,以供其他程序使用。当使用from module import *
语句时,只会导入__all__
中定义的属性、方法和类。如果__all__
未定义,则默认导入所有不以下划线开头的属性、方法和类。需要注意的是,__all__
只对from module import *
语句起作用,对于其他导入方式,如import module
和from module import name
,__all__
不会生效。因此,在编写模块时,应该避免使用from module import *
语句,而应该显式地导入需要的内容。
# module.py def public_function(): pass def _private_function(): pass class PublicClass: pass class _PrivateClass: pass __all__ = ['public_function', 'PublicClass']
# 在使用from module import *
语句导入模块时,只会导入public_function
和PublicClass
,而不会导入_private_function
和_PrivateClass
补充知识:
python内置函数 dir()、globals()、locals()
dir():查看当前范围或参数范围内的信息,包括属性、方法、类、变量等
""" 当不带参数调用dir()函数时,它返回当前范围内的变量、方法和定义的类型列表。当调用dir()函数时带参数,它返回参数的属性和方法列表。如果参数包含__dir__()方法,
该方法将被调用。如果参数不包含__dir__()方法,dir()函数将最大限度地收集参数信息。 """
dir() # 当前模块
dir(math) # 查看math类里的所有属性,方法globals():