2016-11-11 36 views
1

我有一個基類Base是在模塊base.py的模塊名稱。獲取類對象哪個模塊__main__

class Base: 
    def __init__(self): 
     print(self.__module__) 

此外,還有一個子類Child是在模塊child.py

from test.base import Base 

class Child(Base): 
    pass 

if __name__ == '__main__': 
    c = Child() 

我運行了python child.py。 我想聲明print(self.__module__)打印childchild.py,不__main__因爲它是目前印刷。

P.S.如果沒有在子類

回答

0

實際上重新定義初始化方法,我不知道你真正的意思。 但我認爲isinstance()會幫助你。

在the__init__of基類:

if isinstance(obj, Child): 
    self.__module__ = "Child" 

或只使用self.__class__

+0

這不是我的意思。如果我有很多類的複雜'mro',我需要像我有課程那樣編寫很多'if isinstance'? – hasam

+0

試試'self .__ class__'? – Jing

0

__file__將包含 'child.py' 爲您服務。

print(__file__) 
0

而不是把功能直接在if __name__ == '__main__'塊的,定義一個main功能。然後,在if __name__ == '__main__'塊,導入從child模塊main功能和運行該版本:

import test.base 

class Child(test.base.Base): 
    pass 

def main(): 
    ... 

if __name__ == '__main__': 
    # Even though this is child.py, it's not the child module. 
    # Import main from the child module so we get the right Child class. 
    import child 
    child.main() 
相關問題