【问题标题】:Get module name of class object which module is __main__获取模块是__main__的类对象的模块名
【发布时间】:2016-11-11 10:07:33
【问题描述】:

我有一个基类 Base,它位于模块 base.py 中。

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__) 打印 childchild.py,而不是当前打印的 __main__

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

【问题讨论】:

    标签: python python-3.x oop


    【解决方案1】:

    不要将功能直接放在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()
    

    【讨论】:

      【解决方案2】:

      __file__ 将为您包含“child.py”。

      print(__file__)
      

      【讨论】:

        【解决方案3】:

        实际上,我不确定您的真正意思。 但我认为isinstance() 会帮助你。

        在基类的__init__中:

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

        或者直接使用self.__class__

        【讨论】:

        • 我不是这个意思。如果我有复杂的mro 有很多类,我需要写这么多if isinstance,因为我有类?
        • 试试self.__class__ ?
        猜你喜欢
        • 2010-10-11
        • 2020-06-26
        • 1970-01-01
        • 2022-10-18
        • 2011-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-30
        相关资源
        最近更新 更多