Skip to main content
 首页 » 编程设计

python之获取模块为 __main__ 的类对象的模块名称

2025年04月02日9lexus

我在模块 base.py 中有一个基类 Base。

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

此外,在模块 child.py 中还有一个子类 Child。

from test.base import Base 
 
class Child(Base): 
    pass 
 
if __name__ == '__main__': 
    c = Child() 

我运行 python child.py。 我想要语句 print(self.__module__) 来打印 child 或 child.py,而不是 __main__当前打印。

附言无需在子类中重新定义 init 方法

请您参考如下方法:

与其将功能直接放在 if __name__ == '__main__' block 中,不如定义一个 main 函数。然后,在 if __name__ == '__main__' block 中,从 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()