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.
Thanks,
Ryan 11 1524
"Ryan Krauss" <ry*******@gmai l.com> wrote in message
news:ma******** *************** *************** *@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(objec t):
def __init__(self):
# do common base class stuff here
print "doing common base functionality"
class SpecialCoolClas s(BaseClass):
def __init__(self,s pecialArg1, coolArg2):
# invoke common initialization stuff
# (much simpler than extracting lines of source code and
# mucking with them)
super(SpecialCo olClass,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 = SpecialCoolClas s("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
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_param s):
for key, value in unknown_params:
setattr(self, key, value)
HTH,
Diez
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 <pt***@austin.r r._bogus_.com> wrote: "Ryan Krauss" <ry*******@gmai l.com> wrote in message news:ma******** *************** *************** *@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(objec t): def __init__(self): # do common base class stuff here print "doing common base functionality"
class SpecialCoolClas s(BaseClass): def __init__(self,s pecialArg1, coolArg2): # invoke common initialization stuff # (much simpler than extracting lines of source code and # mucking with them) super(SpecialCo olClass,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 = SpecialCoolClas s("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
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.
Why ? Python is dynamic enough to let you modify classes at runtime...
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Because I want to store the results in one place so that in order to
use the code later, all I have to do is import the classes that
include the parameters that were previously unknown. I want to make
using the results as easy and clean as possible for other users.
Ryan
On 4/19/06, bruno at modulix <on***@xiludom. gro> wrote: 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.
Why ? Python is dynamic enough to let you modify classes at runtime...
-- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'on***@xiludom. gro'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
"Ryan Krauss" <ry*******@gmai l.com> wrote in message
news:ma******** *************** *************** *@python.org...
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.
You are talking about writing code from and to a file. I think I had a
similar problem, because I wanted a python class to contains some persistent
runtime variables (fx the date of last backup) I didn't found a solution in
the python library so I wrote a little class myself:
import cPickle
class Persistent:
def __init__(self,f ilename):
self.filename=f ilename
def save(self):
f=file(self.fil ename, 'wb')
try:
for i in vars(self):
val=vars(self)[i]
if not i[0:2]=='__':
cPickle.dump(i, f)
cPickle.dump(va l,f)
finally:
f.close()
def load(self):
f=file(self.fil ename)
try:
while True:
name=cPickle.lo ad(f)
value=cPickle.l oad(f)
setattr(self,na me,value)
except EOFError:
f.close()
f.close()
You just use it like (the file has to exist - easy to change):
p=Persistent('f ile.obj')
p.load()
p.a=0.12345
p.b=0.21459
p.save()
Ryan Krauss wrote:
(top-post corrected) On 4/19/06, bruno at modulix <on***@xiludom. gro> wrote:
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 identificati on 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. Why ? Python is dynamic enough to let you modify classes at runtime...
Because I want to store the results in one place so that in order to use the code later, all I have to do is import the classes that include the parameters that were previously unknown. I want to make using the results as easy and clean as possible for other users.
I'm afraid you're still thinking in terms of the solution instead of
thinking in terms of the problem to solve. The fact that classes can be
modified at runtime doesn't means that client code needs to be aware of
what happens.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'on***@xiludom. gro'.split('@')])"
It turns out that what I want to do can be done using the inspect
module which has methods for getsourcecode among other things.
Ryan
On 4/19/06, bruno at modulix <on***@xiludom. gro> wrote: Ryan Krauss wrote: (top-post corrected) On 4/19/06, bruno at modulix <on***@xiludom. gro> wrote:
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 identificati on 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.
Why ? Python is dynamic enough to let you modify classes at runtime...
Because I want to store the results in one place so that in order to use the code later, all I have to do is import the classes that include the parameters that were previously unknown. I want to make using the results as easy and clean as possible for other users.
I'm afraid you're still thinking in terms of the solution instead of thinking in terms of the problem to solve. The fact that classes can be modified at runtime doesn't means that client code needs to be aware of what happens.
-- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'on***@xiludom. gro'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
> It turns out that what I want to do can be done using the inspect module which has methods for getsourcecode among other things.
I never said that what you wanted to do was impossible (nor even
difficult, and FWIW, there are simpler alternatives than using inspect
- using a templating system like empy comes to mind...). I only suggest
that there are possibly far better solutions, that you seem to dismiss
for some unknown reason... This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Daniel Corbett |
last post by:
I am trying to save a file dynamically created in a webpage. I get the
following headers, but cannot figure out how to save the attachment. I am
basically trying to replicate what internet explorer would do in this case.
The headers I am getting are:
Headers {Content-Disposition: attachment; filename="dynamic_file.mdb"
Connection: close
Cache-Control: private
Content-Type: application/octet-stream
|
by: jimfollett1 via DotNetMonster.com |
last post by:
Hey all,
I was wondering if you could put me out of my misery (hopefully, not literaly)
..
I am currently trying to port some VB6 code to VB.NET because of a possible
significant performance improvement on a very large simulation based system.
All my variables are currently encapsulated in public UDTs. If I could
access these COM UDTs from a .NET dll, I will be sorted for porting the
important engine of the system without having to...
|
by: Stephan Zaubzer |
last post by:
Hi
I relatively new to C# and at the moment I am having troubles accessing
com objects within C#.
I am working in VS.net. I add the com library I want to access to my
references. Accessing classes exported in this com interfaces will throw
a System.Security.SecurityException.
(System.Security.Permissions.SecurityPermission)
Status of failed permission:
<IPermission class="System.Security.Permissions.SecurityPermission,
|
by: Cyril Gupta |
last post by:
Hello,
I have a class inside another class. The Scenario is like Car->Engine, where
Car is a class with a set of properties and methods and Engine is another
class inside it with its own set of properties.
I want to know if there is a way to access the methods and the properties of
the Owner class for the class that's inside it? I.e. I want to find out
within Engine what make the Car is which is exposed by the property
Car.Model.
|
by: Jimmy Reds |
last post by:
Hi,
I have a blood glucose meter (a Lifescan OneTouch Ultra in case anyone
was wondering) which I connect to my PC using a USB cable and I would
like to have a go at accessing the data on this device without having
to use the software provided by Lifescan. The software is free and is
okay but it's not very good at manipulating the data.
Although I connect my meter using a USB cable, it can be connected by a
serial cable (there is a...
| |
by: eholz1 |
last post by:
Hello php group,
I have a dev server running php 5.0 and apache 2.2, I have created
some php files that create classes, etc All works well with this.
But when I copy the files to my hosting service's server - I get the
following error :
Parse error: parse error, unexpected T_CLASS in /home/3/2/2/3468/3468/
usr/include/classes/Portfolio.php on line 2.
|
by: GesterX |
last post by:
Hi guys, this has been bugging me for a while and I'd appreciate any help anyone could offer.
Basically I am running a boating simulation and I have all of the "harder" parts done but one error is holding me back from compiling my code.
I won't go into detail about the simulation but basically I have a Boat super class and extended from this are the sub classes; cruiser, speedboat, and jetski.
My problem is when it comes to accessing...
|
by: djsuson |
last post by:
I'm trying to set up an inheritance tree that also uses templates. This is an attempt to simplify some previous code that was filled with redundancies. I'm working with g++ 3.4.6. The code is split over four files: two headers and two implamentation files, but uses the include trick mentioned on another thread to connect the header and implamentation files together. The base class header is
#ifndef _BASEDATA_H_
#define _BASEDATA_H_
...
|
by: fgh.vbn.rty |
last post by:
Say I have a base class B and four derived classes d1, d2, d3, d4. I
have three functions fx, fy, fz such that:
fx should only be called by d1, d2
fy should only be called by d2, d3
fz should only be called by d1, d3, d4
I think I have two options.
(1) Make all functions virtual and define them in the required derived
classes. This will of course lead to a lot of code duplication and
problems in maintainability.
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |