Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Child class name in parent class function at run time Python

Tags:

python

Is it possible to find out which child class has called the parent class function in the parent class function

class ParentClass:

    def print_child_class_name(self):
        print('how to find print the child class name here')

class ChildClass1(ParentClass):
    pass

class ChildClass2(ParentClass):
   pass

child_1 = ChildClass1()
child_2 = ChildClass2()
child_1.print_child_class_name()
child_2.print_child_class_name()
like image 507
Satish Avatar asked Oct 19 '25 01:10

Satish


1 Answers

You'd use: self.__class__.__name__ to retrieve the name of the class of the instance self.

class ParentClass:

    def print_child_class_name(self):
        print(self.__class__.__name__)

class ChildClass1(ParentClass):
    pass

class ChildClass2(ParentClass):
   pass

child_1 = ChildClass1()
child_2 = ChildClass2()
child_1.print_child_class_name() #Prints ChildClass1
child_2.print_child_class_name() # Prints ChildClass2
like image 114
UltraInstinct Avatar answered Oct 21 '25 18:10

UltraInstinct



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!