簡體   English   中英

如何使用Python獲取當前文件,當前類和當前方法?

[英]How do I get the current file, current class, and current method with Python?

  • 運行代碼的文件的名稱
  • 運行代碼的類的名稱
  • 代碼運行的方法的名稱(類的屬性)

以下是每個例子:

from inspect import stack

class Foo:
    def __init__(self):
        print __file__
        print self.__class__.__name__
        print stack()[0][3]

f = Foo()
import sys

class A:
    def __init__(self):
        print __file__
        print self.__class__.__name__
        print sys._getframe().f_code.co_name

a = A()

非常小心。 考慮:

class A:
    pass

B = A
b = B()

這里b的“班級名稱”是什么? 是A還是B? 為什么?

關鍵是,你不應該知道或關心。 對象就是這樣的:它的名字很少有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM