Is there a way to flag class declarations so that later you can get a list of them flagged?
Or a way to get all classes starting with a certain string ?
Or all classes that are a subclass of a specific class?
Is there a way to flag class declarations so that later you can get a list of them flagged?
Or a way to get all classes starting with a certain string ?
Or all classes that are a subclass of a specific class?
You can also use metaclasses to collect up the classes as they are defined:
class AllSeeingMetaClass(type):
# This will be a list of all the classes that use us as a metaclass.
the_classes = []
def __new__(meta, classname, bases, classDict):
# Invoked as new classes are defined.
print "Defining %r" % classname
new_class = type.__new__(meta, classname, bases, classDict)
meta.the_classes.append(new_class)
return new_class
class MyBase(object):
# A base class that pulls in our metaclass.
__metaclass__ = AllSeeingMetaClass
class Cat(MyBase):
def __init__(self):
pass
class Dog(MyBase):
def __init__(self):
pass
print AllSeeingMetaClass.the_classes
prints:
Defining 'MyBase'
Defining 'Cat'
Defining 'Dog'
[<class '__main__.MyBase'>, <class '__main__.Cat'>, <class '__main__.Dog'>]
To get a list of subclasses of your class from within itself, use the __subclasses__ method from the parent class.
>>>class Parent(object):
... pass
...
>>>class Child(Parent):
... pass
...
>>>Parent.__subclasses__()
>>>[<class '__main__.Child'>]
Unfortunately there is a dearth of documentation on this method.