Rolfsky
Rolfsky

Reputation: 73

Is there a way to get the class Name from where I create an instance of another class by importing it?

Given:

Module A.py
    class utilities:
        
        def __init__(self):
            #Is there a way to get the class that instantiates this constructor ? But here, in the init method?
            
        def utilMethod(self):
            pass


Module B.py
from A import utilities

    class dummy:
    
        utils = utilities()
        
        def dummyMthod(self):
            utils.utilMethod()
            

#Is there a way to get the class that instantiates utilities class constructor ? But in the init method of the class being instanciated?

Upvotes: 1

Views: 51

Answers (2)

Nir Alfasi
Nir Alfasi

Reputation: 53565

Since you're instantiating utils as a static variable, at the time of its creation class dummy is not yet available so the answer is "no": you can't do that.

Alternative solution: "pass yourself in" (see code comments for explanations)

class utilities:

    def __init__(self):
        pass

    def utilMethod(self, obj):  # the caller is passed in
        print(obj.__class__.__name__) # this is how we can access the class-name of the caller
        pass

class dummy:
    utils = utilities()

    def dummyMthod(self):
        self.utils.utilMethod(self) # here we "pass ourselves in"


d = dummy()
d.dummyMthod() # prints "dummy"

UPDATE

If we want to declare utils as an object attribute (vs. static class attribute in the previous snippet), we can do:

class utilities:

    def __init__(self, obj):
        print(obj.__class__.__name__)
        pass

    def utilMethod(self, obj):
        pass

class dummy:

    def __init__(self):
        self.utils = utilities(self) # declare utils as object attribute inside the constructor and pass 'self' into utilities

    def dummyMthod(self):
        self.utils.utilMethod()


d = dummy() # prints "dummy"

Upvotes: 1

Jiří Baum
Jiří Baum

Reputation: 6940

Within __init__ (and generally within the methods of the class) you can use self.__class__ and/or self.__class__.__name__; the latter can be particularly useful for logging and similar messages.

self.logger = logging.getLogger(self.__class__.__name__)

(Or similar, perhaps also incorporating the module name.)

Upvotes: 0

Related Questions