How to Create Automatically a Instance of Every Class in a Directory

How do I create automatically a instance of every class in a directory?

You can use the ObjectSpace to find the new classes and then instantiate them.

def load_and_instantiate(class_files)
# Find all the classes in ObjectSpace before the requires
before = ObjectSpace.each_object(Class).to_a
# Require all files
class_files.each {|file| require file }
# Find all the classes now
after = ObjectSpace.each_object(Class).to_a
# Map on the difference and instantiate
(after - before).map {|klass| klass.new }
end

# Load them!
files = Dir.glob("path/to/dir/*.rb")
objects = load_and_instantiate(files)

How do I dynamically create instances of all classes in a directory with python?

So I managed to figure out how to do this.

Here's the code for it:

import os
import imp
import inspect

obj_list = []

dir_path = os.path.dirname(os.path.realpath(__file__))
pattern = "*.py"

for path, subdirs, files in os.walk(dir_path):
for name in files:
if fnmatch(name, pattern):
found_module = imp.find_module(name[:-3], [path])
module = imp.load_module(name, found_module[0], found_module[1], found_module[2])
for mem_name, obj in inspect.getmembers(module):
if inspect.isclass(obj) and inspect.getmodule(obj) is module:
obj_list.append(obj())

How can I automate the creation of instances of a class?

# Create Class 
class Player:
def greating(self):
print 'Hello!'

# List to store instanses
l = []

for i in range(4):
l.append(Player())

# Call Instance #1 methods
l[0].greating()

Here we have a player class and 4 instances from this class stored in l list.

Instantiating all classes in directory

Here is a way to auto-register artisan commands. (This code was adapted from the Symfony Bundle auto-loader.)

function registerArtisanCommands($namespace = '', $path = 'app/commands')
{
$finder = new \Symfony\Component\Finder\Finder();
$finder->files()->name('*Command.php')->in(base_path().'/'.$path);

foreach ($finder as $file) {
$ns = $namespace;
if ($relativePath = $file->getRelativePath()) {
$ns .= '\\'.strtr($relativePath, '/', '\\');
}
$class = $ns.'\\'.$file->getBasename('.php');

$r = new \ReflectionClass($class);

if ($r->isSubclassOf('Illuminate\\Console\\Command') && !$r->isAbstract() && !$r->getConstructor()->getNumberOfRequiredParameters()) {
\Artisan::add($r->newInstance());
}
}
}

registerArtisanCommands();

If you put that in your start/artisan.php file, all commands found in app/commands will be automatically registered (assuming you follow Laravel's recommendations for command and file names). If you namespace your commands like I do, you can call the function like so:

registerArtisanCommands('App\\Commands');

(This does add a global function, and a better way to do this would probably be creating a package. But this works.)

How can instances of classes be automatically generated in python?

look into a module called time

you would need to do something like this:

import time

nSeconds = 11
t0 = time.clock()
dt = 0
enemyCount = 0

# the following would be in an appropriate
# place in the main game loop
if dt < nSeconds:
t1 = time.clock()
dt = t1 - t0
else:
enemyInstance = Enemy()
enemyCount += 1
t0 = time.clock()
dt = 0

you can keep track of the enemy count just in case you want to send a special wave after a number of enemies or give bonus points or whatever.

also have a look at this book about game development in python for other ideas: http://inventwithpython.com/makinggames.pdf

In C# is it possible to instantiate all class found in a namespace?

Based on your requirements, and your latest comment suggesting you would accept reflection, I suggest the following:

// add any assemblies you want to discover scripts in here
var assemblies = new[] { System.Reflection.Assembly.GetExecutingAssembly() };

var scriptTypes = assemblies
// get the declared types for each and every assembly
.SelectMany(a => a.GetTypes())
// filter so that we ignore BaseClass, only accept types assignable to base class,
// don't accept abstract classes and only accept types with a parameterless constructor
.Where(t => t != typeof(BaseClass) && typeof(BaseClass).IsAssignableFrom(t) && !t.IsAbstract && t.GetConstructors().Any(c => c.GetParameters().Length == 0));

// create an instance of each type and construct a list from it
var scripts = scriptTypes
.Select(t => (BaseClass)Activator.CreateInstance(t))
.ToList();

How to automatically call classes in Ruby script from a specific directory

First you need to create an array of class names:

>> klasses = Dir["lib/*.rb"].map {|file| File.basename(file, '.rb').camelize.constantize }

Then you can call your method on each of them in turn:

>> klasses.each { |klass| klass.remove_user }

If you are not using Rails, you can require ActiveSupport's String extension methods (require 'active_support/core_ext/string'), which will give you the camelize and constantize methods.



Related Topics



Leave a reply



Submit