python之if __name__ == “__main__”詳解 || python獲取當前運行程序的類名和方法名 || python獲取當前程序運行程序的模塊名


if __name__  == “__main__”:

詳細解釋:

1、每個python模塊都包含內置的變量 __name__ 。( __name__ 是python的一個內置類屬性,它天生就存在於一個 python 程序中,代表對應程序名稱)

2、當在自身模塊里執行的時候, __name__ 等於當前執行文件的名稱【模塊名】(包含了后綴.py)但是又由於 '__main__' 等於當前執行文件的名稱【模塊名】(包含了后綴.py)。進而當模塊被直接執行時, __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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM