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是父类,Test2Test3是其子类,现在想在Test1父类中获取调用子类的文件路径,应该怎么做呢?

解决方案

尝试过的解决方案有:

  1. os.getcwd获取当前工作空间目录,再拼接子类文件名child.py。这种方式依赖工作空间目录路径,如果工作空间目录变动,得到的值是错误的,这种方式不好。
  2. os.path.abs(__file__)获取父类文件路径,再匹配子类文件名,但是目录child1child2属于不同路径,这种方式也不行。
  3. 可行方案:使用__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__可以获取当前类实例所在的类,即子类Test2Test3
  • inspect.getmodule返回类对象是在哪个模块中定义的,即返回一个模块对象。在python中,inspect模块提供了四种主要的功能:类型检查,获取源代码,检查类与函数,检查解释器和调用堆栈。
  • __file__是一个内置变量,用于获取当前模块的文件路径。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值