Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize all the classes in a module into nameless objects in a list

Tags:

python

oop

Is there a way to initialize all classes from a python module into a list of nameless objects?

Example I have a module rules which contains all child classes from a class Rule. Because of that, I'm certain they will all implement a method run() and will have a attribute name which will be generated during the call of __init__

I would like to have a list of objects dynamically initiated from those classes. By dynamically initialized i mean that they don't have to be named explicitly.

The questions are:

Is it possible to iterate through all classes in a module?

Can a nameless object be initiated?

like image 893
TheMeaningfulEngineer Avatar asked Aug 19 '13 14:08

TheMeaningfulEngineer


People also ask

How do you initialize a class object in Python?

Python Object Initialization When we create object for a class, the __init__() method is called. We use this to fill in values to attributes when we create a object. Here, __init__() has two attributes apart from 'self'- color and shape. Then, we pass corresponding arguments for these at the time of object creation.

How do you initialize attributes in Python?

Use the __init__() method to initialize the object's attributes. The __init__() doesn't create an object but is automatically called after the object is created.

What are classes and objects in Python?

An object is simply a collection of data (variables) and methods (functions) that act on those data. Similarly, a class is a blueprint for that object. We can think of a class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows, etc.

How do you create an instance of an object in Python?

Use the class name to create a new instance Call ClassName() to create a new instance of the class ClassName . To pass parameters to the class instance, the class must have an __init__() method. Pass the parameters in the constructor of the class.


1 Answers

There are at least two approaches you can take. You can get all of the subclasses of a class by calling a class's __subclasses__() method. So if your parent class is called Rule, you could call:

rule_list = [cls() for cls in Rule.__subclasses__()]

This will give you all subclasses of Rule, and will not limit them to the ones found in a particular module.

If you have a handle to your module, you can iterate over its content. Like so:

import rule
rule_list = []
for name in dir(rule):
    value = getattr(rule, name)
    if isinstance(value, type) and issubclass(value, Rule):
        rule_list.append(value())

Unfortunately, issubclass throws TypeError if you give it an object that is not a class as its first argument. So you have to handle that somehow.

EDIT: dealing with the issubclass quirk per @Blckknght's suggestion.

like image 93
Matt Anderson Avatar answered Oct 20 '22 09:10

Matt Anderson