Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python get child class inside parent class static/class method

The output of:

class Dog():
    def get_class():
        return __class__

class Cat():
    def get_class():
        return __class__

print(Dog.get_class())
print(Cat.get_class())

is:

<class '__main__.Dog'>
<class '__main__.Cat'>

I want to DRY up my code with a subclass. But the output of:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class BaseClass():
    def get_class():
        return __class__

class Dog(BaseClass):
    pass

class Cat(BaseClass):
    pass

print(Dog.get_class())
print(Cat.get_class())

is

<class '__main__.BaseClass'>
<class '__main__.BaseClass'>

How do I change the code in the second case to obtain the same output as the first case?

>Solution :

you are almost there :

class BaseClass:
    @classmethod
    def get_class(cls):
        return cls

class Dog(BaseClass):
    pass


class Cat(BaseClass):
    pass

print(Dog.get_class())
print(Cat.get_class())

<class '__main__.Dog'>
<class '__main__.Cat'>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading