Dynamic Class Building? 
Author Message
 Dynamic Class Building?

Hello again,

I am working on a system which would benifit from the ability to build
classes dynamically. The system will consist of a basic set of simple
objects, plus a library of functions. I would like to build classes on the
fly, built from the base classes plus some of the functions from the
library as methods.

I thought I'd ask to see if anyone had any suggestions now, before settling
on some other way (ie. I could dynamically build the instances, then copy
them as needed). I am fairly new to python and thought there might be a
better way.

Thanks in advance for any input.

--

John Eikenberry

______________________________________________________________
"A society that will trade a little liberty for a little order
 will deserve neither and lose both."
                                         --B. Franklin



Sun, 02 Apr 2000 03:00:00 GMT  
 Dynamic Class Building?

Quote:

> Hello again,

> I am working on a system which would benifit from the ability to build
> classes dynamically. The system will consist of a basic set of simple
> objects, plus a library of functions. I would like to build classes on the
> fly, built from the base classes plus some of the functions from the
> library as methods.

Just use the class statement where you want the new class.

  def newclass():
     class c(someBaseClass):
        f1=theLibrary.f1
        f2=theLibrary.f2
        # ...

     return c

Jim



Sun, 02 Apr 2000 03:00:00 GMT  
 Dynamic Class Building?

Jim and Frank, Thanks.

That was just what I had in mind. I had read about this type of thing
somewhere before, I think I must have had some sort of mental block. [shrug]

Just outa curiousity, I was thinking about what possible benefits could be
gained from doing this via a class and a __call__ method. I'll probably play
around with both ways and see what I find. Any reason I should avoid using
the class method (you both used a function to create the new class, I
figured there might be a reason).

Thanks again for the tip.

--

John Eikenberry

______________________________________________________________
"A society that will trade a little liberty for a little order
 will deserve neither and lose both."
                                         --B. Franklin



Sun, 02 Apr 2000 03:00:00 GMT  
 Dynamic Class Building?

In the 1.5 distribution, there's a set of 'metaprogramming' Tools which may
well be of help.  There is an essay as part of the public 1.5a4 documentation
available from the pytohn home page.

scott

| Hello again,
|
| I am working on a system which would benifit from the ability to build
| classes dynamically. The system will consist of a basic set of simple
| objects, plus a library of functions. I would like to build classes on the
| fly, built from the base classes plus some of the functions from the
| library as methods.
|
| I thought I'd ask to see if anyone had any suggestions now, before settling
| on some other way (ie. I could dynamically build the instances, then copy
| them as needed). I am fairly new to python and thought there might be a
| better way.
|
| Thanks in advance for any input.
|
| --
|
| John Eikenberry

| ______________________________________________________________
| "A society that will trade a little liberty for a little order
|  will deserve neither and lose both."
|                                        --B. Franklin



Sun, 02 Apr 2000 03:00:00 GMT  
 Dynamic Class Building?

Quote:

> John A Eikenberry writes:
>  > Jim and Frank, Thanks.
>       ^^^^^  Argh!

Opps... Sorry bout that Fred.

Thanks for the interesting information. I think it sounds like I would be
better off just using the class maker function. I don't see any benifits
to being able to trap methods for my purposes. The reason I thought of the
class/__call__ version in the first place was the idea that the class
could be used to store information on previous instances it had built (I'd
like it to remember what classes it's made have been successful and which
ones haven't been).  But I suppose that it would be better to just make
the newclass function a method in a class, and store the info that way,
instead of using the __call__ method.

Fred... thanks again. :)

--

John Eikenberry

______________________________________________________________
"A society that will trade a little liberty for a little order
 will deserve neither and lose both."
                                         --B. Franklin



Sun, 02 Apr 2000 03:00:00 GMT  
 Dynamic Class Building?

Quote:
John A Eikenberry writes:

 > I am working on a system which would benifit from the ability to build
 > classes dynamically. The system will consist of a basic set of simple
 > objects, plus a library of functions. I would like to build classes on the
 > fly, built from the base classes plus some of the functions from the
 > library as methods.

John,
  Try something like this:

def newclass(name, members={}, bases=None):
    temp = {}
    if bases:
        basestr = "("
        sep = ""
        for klass in bases:
            temp[klass.__name__] = klass
            basestr = "%s%s%s" % (basestr, sep, klass.__name__)
            sep = ", "
        basestr = basestr + ")"
    else:
        basestr = ""
    exec ("class %s%s: pass" % (name, basestr)) in temp
    myclass = temp[name]
    myclass.__dict__.update(members)
    return myclass

  Call this function with the name of the class.  The members and
bases can be set to fill in the new class's __dict__ and __bases__
fields.  The only real restriction is that the names of the immediate
base classes must be unique within the bases tuple (not typically a
problem).  The members dictionary can have values which are functions
expecting the first parameter to be the "self" object.
  Methods can be filled in on a class later as well:

def meth(self):
   print self

myclass = newclass("MyClass")
myclass.meth = meth

  I hope this helps!

  -Fred

--
Fred L. Drake, Jr.

Corporation for National Research Initiatives
1895 Preston White Drive
Reston, VA    20191-5434



Sun, 02 Apr 2000 03:00:00 GMT  
 Dynamic Class Building?

Quote:
John A Eikenberry writes:

 > Jim and Frank, Thanks.
           ^^^^^  Argh!

 > Just outa curiousity, I was thinking about what possible benefits could be
 > gained from doing this via a class and a __call__ method. I'll probably play
 > around with both ways and see what I find. Any reason I should avoid using
 > the class method (you both used a function to create the new class, I

  I think using a __call__ method doesn't make a lot of sense.  On the
other hand, defining a class which can support a range of classes
based on input parameters & method calls with a __call__ method to
create instances might make a little more sense.

class InstanceBuilder:
    def __init__(self, name, bases=None, members={}):
        temp = {}
        if bases:
            basestr = "("
            sep = ""
            for base in bases:
                basestr = "%s%s%s" % (basestr, sep, base.__name__)
                temp[base.__name__] = base
                sep = ", "
            basestr = basestr + ")"
        else:
            basestr = ""
        exec ("class %s%s: pass" % (name, basestr)) in temp
        myclass = temp[name]
        myclass.__dict__.update(members)
        self.__class = myclass

    def __call__(self, *args, **kw):
        return apply(self.__class, args, kw)

  This does the same as the example I posted previously, and can be
used like this:

def myinit(self, *args, **kw):
    print args
    if kw: print kw

Quote:
>>> builder = InstanceBuilder("MyClass", members={"__init__": myinit})
>>> instance = builder(1, 2, something="else")

(1, 2)
{'something': 'else'}

  The main difference here is that an instance of InstanceBuilder is
*not* a class object, and won't behave like one other than creating an
instance when called.  This might be ok, and might offer other
advantages (perhaps by providing some form of trapping for methods
provided in the members dictionary, or otherwise performing
indirection), but I don't see that any of those things are being done
that can't be done while still using ordinary class objects to get the
job done.  Most of the overhead can be avoided by creating a class
object and being done with it.
  And partly it may just be a style thing.

  -Fred

--
Fred L. Drake, Jr.

Corporation for National Research Initiatives
1895 Preston White Drive
Reston, VA    20191-5434



Sun, 02 Apr 2000 03:00:00 GMT  
 Dynamic Class Building?

Hey Vladimir,

Thanks for the input, this is what I had been working with. But what I was
looking for was a way to dynamically build classes (not instances). I want
to be able to do is create a class, possibly make several instances of it,
then store it for later use (if it was a 'good' class).

Thanks again for the help,

--

John Eikenberry

______________________________________________________________
"A society that will trade a little liberty for a little order
 will deserve neither and lose both."
                                         --B. Franklin



Mon, 03 Apr 2000 03:00:00 GMT  
 Dynamic Class Building?

Looking over this a little more closely (and comparing it to Jim's), I
have a question.

Your newclass function seems to allow for multiple inhereitance, whereas
Jim's couldn't. Besides this, is there anything that this implimentation
allows that Jim's doesn't (assuming that you filled in a few blanks in
Jims, like passing in the members).

Quote:
>   I hope this helps!

It did. Thanks.

PS. Sorry again for that name mix up.

John Eikenberry

______________________________________________________________
"A society that will trade a little liberty for a little order
 will deserve neither and lose both."
                                         --B. Franklin



Mon, 03 Apr 2000 03:00:00 GMT  
 Dynamic Class Building?

Quote:
John Eikenberry [MSAI] writes:

 > Your newclass function seems to allow for multiple inhereitance, whereas
 > Jim's couldn't. Besides this, is there anything that this implimentation
 > allows that Jim's doesn't (assuming that you filled in a few blanks in
 > Jims, like passing in the members).

  Not really.  The differences between the function I wrote and the
one Jim wrote primarily differed in style; mine is a little more
general and lower-level; Jim's could also be implemented using mine:

def jims_newclass():
    return freds_newclass("c", (someBaseClass,),
                          {"f1": theLibrary.f1,
                           "f2": theLibrary.f2,
                           # ...
                           }

  If Jim's is all you need, it's more efficient and certainly easily
understood, so that should do quite well.  One the other hand, I'm not
sure why you would need multiple class objects for the same class,
unless you want to populate them differently after construction
(perhaps after some of the initial objects have been created).  But
that depends pretty heavily on your application.

  -Fred

--
Fred L. Drake, Jr.

Corporation for National Research Initiatives
1895 Preston White Drive
Reston, VA    20191-5434



Mon, 03 Apr 2000 03:00:00 GMT  
 Dynamic Class Building?

Hello all,

    As I remember, we have a possible to possible to edit __class__.__dict__
and other internal structures.

Quote:
>objects, plus a library of functions. I would like to build classes on the

And way:
## Empty class
class A:
    ## Register method in the object
    def regMethod(self, method):
        self.__class__.__dict__[method.__name__] = method
    ## Register value in the object
    def regVar(self, name, ilitval):
        self.__class__.__dict__[name] = initval
## Some free method
def hello(self):
    print "Hello world from",self
a = A()
a.regMethod(hello)
a.hello()
a.regVal("Foo") = "Bar"
-- working fine
Quote:

>______________________________________________________________
>"A society that will trade a little liberty for a little order
> will deserve neither and lose both."
> --B. Franklin



Mon, 03 Apr 2000 03:00:00 GMT  
 Dynamic Class Building?

Quote:

>   Not really.  The differences between the function I wrote and the
> one Jim wrote primarily differed in style; mine is a little more
> general and lower-level; Jim's could also be implemented using mine:

Good. Nice to know I interpreted your code correctly.

Quote:
>   If Jim's is all you need, it's more efficient and certainly easily
> understood, so that should do quite well.  One the other hand, I'm not
> sure why you would need multiple class objects for the same class,
> unless you want to populate them differently after construction
> (perhaps after some of the initial objects have been created).  But
> that depends pretty heavily on your application.

Well, I'll probably end up using something more like Jim's since I don't
plan on using multiple inheritance any. Though I will add the ability to
pass in the superclass and the members.

The reason I'm interested in this is because in my application I am going
to have a few classes (sorta templates, with only data-members) that then
are used to create multiple classes (which will have different methods).
My application is a agent based development environment. Each agent will
have the same basic data structure but different methods. The need the
same data structures so that the methods can be used as building blocks
for any agent.

Thanks again for your help,

John Eikenberry

______________________________________________________________
"A society that will trade a little liberty for a little order
 will deserve neither and lose both."
                                         --B. Franklin



Mon, 03 Apr 2000 03:00:00 GMT  
 Dynamic Class Building?

This is a multi-part message in MIME format.

------=_NextPart_000_0002_01BCDB36.0E71FEC0
Content-Type: text/plain;
        charset="koi8-r"
Content-Transfer-Encoding: 7bit


Quote:
>Hey Vladimir,
John.
>looking for was a way to dynamically build classes (not instances). I want

So, I so sorry, look at this. Most Python platforms are support a new
module. I think it's a best tool for this action :)
Look at small attachment and sample output:
---
Foo A
Bar A
Foo B
Bar B
Grab B 1
---
In this sample I dynamicaly create a small hierarhy A<-B , create two
instances and call a methods. Module new contain many another useful
functions for dynamical creation of classes, instances, functions and so on.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Vladimir Ulogov
WARNING! Spam protection feature, remove ".korea"

------=_NextPart_000_0002_01BCDB36.0E71FEC0
Content-Type: application/octet-stream;
        name="t6.py"
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment;
        filename="t6.py"

import new

def foo(self):
    print "Foo",self.__name__
def bar(self):
    print "Bar",self.__name__
dict = {'__name__':'A','foo':foo, 'bar':bar}

aclass = new.classobj("A", (), dict)
a = aclass()
a.foo()
a.bar()
def grab(self, i):
    print "Grab",self.__name__,i
bdict = {'__name__':'B', 'grab':grab}
bclass = new.classobj("B", (aclass,), bdict)
b = bclass()
b.foo()
b.bar()
b.grab(1)

------=_NextPart_000_0002_01BCDB36.0E71FEC0--



Tue, 04 Apr 2000 03:00:00 GMT  
 
 [ 13 post ] 

 Relevant Pages 

1. dynamic class hierarchies, dynamic changes to multimethods ?

2. problem building a dynamic index

3. How to build a dynamic file structure?

4. Dynamic GUI Building in VA

5. How can I use labview to build a dynamic clamp

6. LV 5.1 App Build and Dynamic Loading

7. Connecting vi's to build a dynamic system

8. Memory read problem when calling dynamic arrays in DLL built using VC++ (LabView 5)

9. Question on building dynamic modules under Win32, Python 1.4

10. building dynamic and static libs at the same time

11. Itcl option to build and install both static and dynamic libraries

12. building tcl dynamic libraries under windows.

 

 
Powered by phpBB® Forum Software