accessing a classes code
Ryan Krauss
ryanlists at gmail.com
Wed Apr 19 12:22:18 EDT 2006
I think this is a lot like I am planning to do, except that the new
classes will be dynamically generated and will have new default values
that I want to specify before I write them to a file. But how do I do
that?
Ryan
On 4/19/06, Paul McGuire <ptmcg at austin.rr._bogus_.com> wrote:
> "Ryan Krauss" <ryanlists at gmail.com> wrote in message
> news:mailman.4754.1145458893.27775.python-list at python.org...
> ======================
> I have a set of Python classes that represent elements in a structural
> model for vibration modeling (sort of like FEA). Some of the
> parameters of the model are initially unknown and I do some system
> identification to determine the parameters. After I determine these
> unknown parameters, I would like to substitute them back into the
> model and save the model as a new python class. To do this, I think
> each element needs to be able to read in the code for its __init__
> method, make the substitutions and then write the new __init__ method
> to a file defining a new class with the now known parameters.
>
> Is there a way for a Python instance to access its own code
> (especially the __init__ method)? And if there is, is there a clean
> way to write the modified code back to a file? I assume that if I
> can get the code as a list of strings, I can output it to a file
> easily enough.
> ======================
>
> Any chance you could come up with a less hacky design, such as creating a
> sub-class of one of your base classes? As in:
>
> class BaseClass(object):
> def __init__(self):
> # do common base class stuff here
> print "doing common base functionality"
>
> class SpecialCoolClass(BaseClass):
> def __init__(self,specialArg1, coolArg2):
> # invoke common initialization stuff
> # (much simpler than extracting lines of source code and
> # mucking with them)
> super(SpecialCoolClass,self).__init__()
>
> # now do special/cool stuff with additional init args
> print "but this is really special/cool!"
> print specialArg1
> print coolArg2
>
> bc = BaseClass()
> scc = SpecialCoolClass("Grabthar's Hammer", 6.02e23)
>
> Prints:
> ----------
> doing common base functionality
> doing common base functionality
> but this is really special/cool!
> Grabthar's Hammer
> 6.02e+023
>
> If you're still stuck on generating code, at least now you can just focus
> your attention on how to generate your special-cool classes, and not so much
> on extracting source code from running classes.
>
> -- Paul
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list