python在父类中获取子类的文件路径
背景介绍
分享一种科学的方法,用于从父类中拿到子类的文件路径。 例如有以下项目目录:
-
parent child1 child.py child2 child.py test1.py
文件test1.py的内容是:
import unittest class Test1(unittest.TestCase): def test_parent(self): print("I am parent")
文件child1/child.py的内容是:
from parent.test1 import Test1 class Test2(Test1): def test_child(self): print("I am test2") self.test_parent() test2 = Test2()
文件child2/child.py的内容是:
from parent.test1 import Test1 class Test3(Test1): def test_child(self): print("I am test3") self.test_parent() test2 = Test3()
即Test1是父类,Test2和Test3是其子类,现在想在Test1父类中获取调用子类的文件路径,应该怎么做呢?
解决方案
尝试过的解决方案有:
- os.getcwd获取当前工作空间目录,再拼接子类文件名child.py。这种方式依赖工作空间目录路径,如果工作空间目录变动,得到的值是错误的,这种方式不好。
- os.path.abs(__file__)获取父类文件路径,再匹配子类文件名,但是目录child1和child2属于不同路径,这种方式也不行。
- 可行方案:使用__class__获取当前类实例,再用__file__获取文件路径。
即在父类文件test1.py中这样调用:
class Test1(unittest.TestCase): def test_parent(self): print("I am parent") print(inspect.getmodule(self.__class__).__file__)
调用child1/child.py,得到
I am test2 I am parent /Users/xxing/Documents/project/pythonProject1/test/parent/child1/child.py
调用child2/child.py,得到
I am test3 I am parent /Users/xxing/Documents/project/pythonProject1/test/parent/child2/child.py
解析:
依次拆解来看:
-
self.__class__可以获取当前类实例所在的类,即子类Test2或Test3 inspect.getmodule返回类对象是在哪个模块中定义的,即返回一个模块对象。在python中,提供了四种主要的功能:类型检查,获取源代码,检查类与函数,检查解释器和调用堆栈。 __file__是一个内置变量,用于获取当前模块的文件路径。