accessing a classes code
Diez B. Roggisch
deets at nospam.web.de
Wed Apr 19 12:06:16 EDT 2006
Ryan Krauss wrote:
> 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.
>
> I am tempted to just read in the code and write a little Python script
> to parse it to get me the __init__ methods, but that seems like
> reinventing the wheel.
Use dictionaries for those parameters, and set them on your instances.
class Foo(object):
def __init__(self, **unknown_params):
for key, value in unknown_params:
setattr(self, key, value)
HTH,
Diez
More information about the Python-list
mailing list