

Ask HN: Is there a way to define classes at runtime in any language? - Allocator2008

I was just thinking about chatbots, and the ability to make logical deductions. Like Men are Mortals, Socrates is a man, so Socrates is mortal. So Mortals could be the superclass, men could be the subclass, and Socrates could be an instance of the subclass men, and would be a member of superclass Mortals. But it would be nice to have a way of defining these classes at runtime, so in a chatbot if the user posed such a scenario to the chatbot, the chatbot could use some pattern matching, construct the classes on the fly, and figure out the relations, thereby sounding "intelligent". Can this be done? Classes made at runtime instead of compile time?
======
benhoyt
In Python you can create a class at "runtime" using "type(name, bases, dict)"
as per <http://docs.python.org/library/functions.html#type>

You can also use "new.classobj(name, bases, dict)" -- not quite sure what the
difference is.

------
paulgb
You would probably want to implement your own concept of classes to do this,
in which case you wouldn't have to restrict yourself to languages where
classes could be declared at runtime.

But if you really wanted to use the language's classes, there are languages
that support it. Javascript is one. I think Ruby lets you do this too. Python
lets you declare classes at runtime, but I don't think it gives you as much
flexibility as the former two. Still, any of the three should be powerful
enough to do what you want. Scheme will let you do it too.

------
inklesspen
Certainly you can define classes at runtime. But I think this is the wrong way
to go about logical reasoning. What happens when you want to express that
Socrates is a dead Greek philosopher? Do you have DeadMortal (subclass of
Mortal with isDead() returning true), GreekMortal, PhilosopherMortal (subclass
of UnemployedMortal)?

I think you may get further if you look at a language like Prolog -- work
along the lines of predicates, rules, and attributes.

------
_pius
See this (old) presentation for thinking along these lines:

[http://www.jroller.com/obie/entry/deep_integration_of_ruby_a...](http://www.jroller.com/obie/entry/deep_integration_of_ruby_and)

------
stonemetal
There are several languages that allow dynamic creation of classes. Any of the
dynamically typed scripting languages can do that javascript, python, perl,
ruby, etc.

