I do something similar to the following to find out and filter the classes I have declared in a module:
class Padre:
None
class Hijo(Padre):
None
c = dir()
for element in c:
if issubclass(eval(element), Padre):
print (element)
# Padre
# Hijo
But what I need is to do this from within one of the classes. Something similar to the following but that works. Because this way all I get is the __dir__
text type attribute '__main__'
.
class Padre:
def __init__(self):
self.h = self.obtenSubClases()
def obtenSubClases(self):
l = []
c = (dir(self.__module__))
for element in c:
if issubclass(eval(element), Padre):
l.append(element)
return l
class Hijo(Padre):
None
For these purposes, I advise you to use the inspect.getmembers
inspect
module and method :The Father class itself is also returned, if we don't want it in the list we can do:
In Python 3 and Python 2 new-style classes (derived from
Object
) we also have the special attribute__subclasses__
that allows us to get the direct subclasses of a given class.In Python >= 3.6 we can override the method
__init__subclass
, which is executed when the class is inherited at any level, and use it to create the list of subclasses dynamically:In all cases the method is a class method, which means that it can be called using the class, without needing an instance of
Padre
: