Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get filename of subclass?

How to get the filename of the subclass?

Example:

base.py:

class BaseClass:
    def __init__(self):
        # How to get the path "./main1.py"?

main1.py:

from base import BaseClass

class MainClass1(BaseClass):
    pass
like image 946
e-info128 Avatar asked Sep 01 '25 00:09

e-info128


1 Answers

Remember that self in BaseClass.__init__ is an instance of the actual class that's being initialised. Therefore, one solution, is to ask that class which module it came from, and then from the path for that module:

import importlib

class BaseClass:
    def __init__(self):
        m = importlib.import_module(self.__module__)
        print m.__file__

I think there are probably a number of way you could end up with a module that you can't import though; this doesn't feel like the most robust solution.

If all you're trying to do is identify where the subclass came from, then probably combining the module name and class name is sufficient, since that should uniquely identify it:

class BaseClass:
    def __init__(self):
        print "{}.{}".format(
            self.__module__,
            self.__class__.__name__
        )
like image 199
SpoonMeiser Avatar answered Sep 02 '25 20:09

SpoonMeiser