Python中if __name__ == '__main__'如何使用?如何获取程序类名及方法名?

2026-05-24 17:591阅读0评论SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计717个文字,预计阅读时间需要3分钟。

Python中if __name__ == '__main__'如何使用?如何获取程序类名及方法名?

pythonif __name__==__main__: # 详细解释: # 1. 每个Python模块都包含一个内置变量__name__。 # (__name__是Python的一个内置属性,它表示当前模块的名称。当模块被直接运行时,__name__的值为 __main__。) # 2. 当在自身环境中运行时,

if __name__ == “__main__”:

详细解释:

1、每个python模块都包含内置的变量__name__。(__name__是python的一个内置类属性,它天生就存在于一个 python 程序中,代表对应程序名称)

2、当在自身模块里执行的时候,__name__等于当前执行文件的名称(包含了后缀.py)但是又由于 '__main__' 等于当前执行文件的名称(包含了后缀.py)。进而当模块被直接执行时,__name__ == '__main__'结果为真。

Python中if __name__ == '__main__'如何使用?如何获取程序类名及方法名?

3、如果该模块被import到其他模块中,则该模块的__name__等于该模块名称(不包含后缀.py)。

python获取当前运行程序的类名和方法名

1、获取当前运行程序的类名:self.__class__.__name__

import sys


class Hello:

def hello(self):
print('the name of method is ## {} ##'.format(sys._getframe().f_code.co_name))
print('the name of class is ## {} ##'.format(self.__class__.__name__))


if __name__ == "__main__":
h = Hello()
h.hello()

运行结果:

the name of method is ## hello ##
the name of class is ## Hello ##

2、获取当前运行程序的方法名

①从函数内部获取函数名:func.__name__

def hello_word():
print(hello_word.__name__)


if __name__ == '__main__':
hello_word() # 运行结果:hello_word

②从函数外部获取函数名:getattr(func, '__name__')

def hello_word():
print('Hello Word!')


if __name__ == '__main__':
hello_word() # 运行结果:Hello_Word!
print(getattr(hello_word, '__name__'))

运行结果:

Hello Word!
hello_word

③从函数内部获取函数本身的名字

# -*- encoding:utf-8 -*-
import sys


def hello_word():
print(sys._getframe().f_code.co_name)


if __name__ == '__main__':
hello_word() # 运行结果:hello_word

④使用inspect模块动态获取当前运行的函数名

import inspect


def get_current_function_name():
return inspect.stack()[1][3]

class MyClass:
def function_one(self):
print "%s.%s invoked"%(self.__class__.__name__, get_current_function_name())
if __name__ == "__main__":
myclass = MyClass()
myclass.function_one()

运行结果:

MyClass.function_one invoked

:一般来说,获取当前运行函数的函数名多用于装饰器函数中,用于调用方法前以及调用方法后;

举例:

# 定义一个装饰器,为修饰测试方法提供附加操作(测试方法调用前,测试方法调用后)
def record(module_name):
def decorate_log(func):
@wraps(func)
def log(*args, **kwargs):
print(f'------{module_name}模块---开始执行{func.__name__}测试脚本------')
try:
func(*args, **kwargs)
except Exception as e:
print(f'------{module_name}模块---{func.__name__}测试脚本执行失败,失败原因:{e}------')
raise e
else:
print(f'------{module_name}模块---{func.__name__}测试脚本执行成功------')

return log

return decorate_log

python获取当前程序运行程序的模块名

import os

module_name = os.path.basename(__file__).split('.')[0]

if __name__ == '__main__':
print(module_name)

去期待陌生,去拥抱惊喜。

本文共计717个文字,预计阅读时间需要3分钟。

Python中if __name__ == '__main__'如何使用?如何获取程序类名及方法名?

pythonif __name__==__main__: # 详细解释: # 1. 每个Python模块都包含一个内置变量__name__。 # (__name__是Python的一个内置属性,它表示当前模块的名称。当模块被直接运行时,__name__的值为 __main__。) # 2. 当在自身环境中运行时,

if __name__ == “__main__”:

详细解释:

1、每个python模块都包含内置的变量__name__。(__name__是python的一个内置类属性,它天生就存在于一个 python 程序中,代表对应程序名称)

2、当在自身模块里执行的时候,__name__等于当前执行文件的名称(包含了后缀.py)但是又由于 '__main__' 等于当前执行文件的名称(包含了后缀.py)。进而当模块被直接执行时,__name__ == '__main__'结果为真。

Python中if __name__ == '__main__'如何使用?如何获取程序类名及方法名?

3、如果该模块被import到其他模块中,则该模块的__name__等于该模块名称(不包含后缀.py)。

python获取当前运行程序的类名和方法名

1、获取当前运行程序的类名:self.__class__.__name__

import sys


class Hello:

def hello(self):
print('the name of method is ## {} ##'.format(sys._getframe().f_code.co_name))
print('the name of class is ## {} ##'.format(self.__class__.__name__))


if __name__ == "__main__":
h = Hello()
h.hello()

运行结果:

the name of method is ## hello ##
the name of class is ## Hello ##

2、获取当前运行程序的方法名

①从函数内部获取函数名:func.__name__

def hello_word():
print(hello_word.__name__)


if __name__ == '__main__':
hello_word() # 运行结果:hello_word

②从函数外部获取函数名:getattr(func, '__name__')

def hello_word():
print('Hello Word!')


if __name__ == '__main__':
hello_word() # 运行结果:Hello_Word!
print(getattr(hello_word, '__name__'))

运行结果:

Hello Word!
hello_word

③从函数内部获取函数本身的名字

# -*- encoding:utf-8 -*-
import sys


def hello_word():
print(sys._getframe().f_code.co_name)


if __name__ == '__main__':
hello_word() # 运行结果:hello_word

④使用inspect模块动态获取当前运行的函数名

import inspect


def get_current_function_name():
return inspect.stack()[1][3]

class MyClass:
def function_one(self):
print "%s.%s invoked"%(self.__class__.__name__, get_current_function_name())
if __name__ == "__main__":
myclass = MyClass()
myclass.function_one()

运行结果:

MyClass.function_one invoked

:一般来说,获取当前运行函数的函数名多用于装饰器函数中,用于调用方法前以及调用方法后;

举例:

# 定义一个装饰器,为修饰测试方法提供附加操作(测试方法调用前,测试方法调用后)
def record(module_name):
def decorate_log(func):
@wraps(func)
def log(*args, **kwargs):
print(f'------{module_name}模块---开始执行{func.__name__}测试脚本------')
try:
func(*args, **kwargs)
except Exception as e:
print(f'------{module_name}模块---{func.__name__}测试脚本执行失败,失败原因:{e}------')
raise e
else:
print(f'------{module_name}模块---{func.__name__}测试脚本执行成功------')

return log

return decorate_log

python获取当前程序运行程序的模块名

import os

module_name = os.path.basename(__file__).split('.')[0]

if __name__ == '__main__':
print(module_name)

去期待陌生,去拥抱惊喜。