2017-01-24 70 views
0

是否可以獲取包含該類的文件的名稱?變量exporter是下面的一個類。如何獲取包含該類的文件的名稱?

def main(exporter): 

    v = exporter 
    print v # <__main__.Vudu object at 0x106ea5210> 
      # The class is "Vudu" and the filename that contains that class 
      # is called vudu_exporter. How would I get "vudu_exporter" ? 

更新:以下作品獲得包含類的腳本的名稱:類/功能/方法/模塊

script_name = os.path.basename(inspect.getfile(v.__class__)) 
+0

'vudo.vudu_exporter .__ file__'應該包含它的名字。 – tdelaney

+0

什麼課?你沒有向我們展示任何課程。 – user2357112

回答

1

呼叫inspect.getfile。它不能保證工作,但它比僅檢查對象的the __file__ attribute(例如,在Python 3.5上,inspect.getfile(collections.defaultdict)工作,而collections.defaultdict.__file__上升AttributeError)更可靠。

如果您有一個實例,如果不先轉換爲類,這將不起作用,例如, inspect.getfile(type(instance))(在Python 2上,instance.__class__對於舊式類可以更可靠);它只能告訴你在什麼地方定義了類,而不是在哪裏定義了實例。