开发者

Getting the module file path of a derived class via inheritance

开发者 https://www.devze.com 2022-12-17 00:29 出处:网络
Suppose you have the following: $ more a.py import os class A(object): def getfile(self): return os.path.abspath(__file__)

Suppose you have the following:

$ more a.py
import os

class A(object):
    def getfile(self):
        return os.path.abspath(__file__)

-

$ more b.py
import a

class B(a.A):
    pass

-

>>> import b
>>> x=b.B()
>>> x.getf开发者_开发百科ile()
'/Users/sbo/tmp/file/a.py'

This is clear. No surprise from this code. Suppose however that I want x.getfile() to return the path of b.py without having to define another copy of getfile() under class B.

I did this

import os
import inspect

class A(object):
    def getfile(self):
        return os.path.abspath(inspect.getfile(self.__class__))

I was wondering if there's another strategy (and in any case, I want to write it here so it can be useful for others) or potential issues with the solution I present.

CW as it's more a discussion question, or a yes/no kind of question


sys.modules[self.__class__.__module__].__file__


Was able to get this working in python 3 as follows:

import os

class Parent:

    def __init__(self, filename=__file__):
        self.filename = filename

    def current_path(self):
        pth, _ = os.path.split(os.path.abspath(self.filename))
        return pth

Then in a different module...

from practice.inheritance.parent import Parent

class Child(Parent):

    def __init__(self):
        super().__init__(__file__)

...accessing current_path() from either Parent or Child returns the respective module path as expected.

>>> from practice.inheritance.parent import Parent
>>> parent = Parent()
>>> print(parent.current_path())
/Users/davidevans/PycharmProjects/play35/practice/inheritance

>>> from practice.inheritance.subpackage.child import Child
>>> child = Child()
>>> print(child.current_path())
/Users/davidevans/PycharmProjects/play35/practice/inheritance/subpackage
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号