Rolfsky
Rolfsky

Reputation: 73

Get module name for Child class that inherits a parent class for the current execution

In ParentModule.py module we have the following class:

class parent:
    def __init__(self):
        #Code that gets the module that inherits this class 
        pass
        
    def parentMethod(self):
        pass
    

In childModule.py module we have the following class:

class child(parent):
    def childMethod(self):
        pass

In externalModule.py module we import and create an instance of child class:

if __name__ == "__main__":
    from childModule.py import child
    childInstance = child()
    childInstance.parentMethod()

Is there a way when externalModule is ran to get the module name for the child class, but the piece of code that does this to be in parent class constructor?

Upvotes: 2

Views: 714

Answers (2)

basckerwil
basckerwil

Reputation: 388

class Parent:
    def __init__(self):
        print(self.__module__)

Upvotes: 4

luther
luther

Reputation: 5564

In the documentation under "Custom classes", it says:

Special attributes:... __module__ is the module name in which the class was defined;

So you can get the module name with type(self).__module__.

Upvotes: 1

Related Questions