2016-11-11 61 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() 
相关问题