473,386 Members | 1,698 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Instantiating classes on the fly

Is there a way in which classes can be instantiated on the fly. I would be passed the name of the file to be instantiated through command line which I store in a variable using getopt.

So the file that needs to be instantiated would be dynamic. How would I achieve that in Python

Thanks
--V
Feb 6 '07 #1
7 2396
bartonc
6,596 Expert 4TB
Is there a way in which classes can be instantiated on the fly. I would be passed the name of the file to be instantiated through command line which I store in a variable using getopt.

So the file that needs to be instantiated would be dynamic. How would I achieve that in Python

Thanks
--V
Hmmm... Maybe you mean instantiate objects on the fly... Anyway, that's what normally happens (on both cases)... To create a file object in your script from a command-line argument, use something like this:

Expand|Select|Wrap|Line Numbers
  1. import sys
  2. # open a file in text mode for reading (create file object)
  3. try:
  4.     fileObj = open(sys.argv[1])
  5.     # print each line as an example of doing something with a file object
  6.     for line in fileObj:
  7.         print line
  8.     fileObj.close()
  9. except (IOError, IndexError):
  10.     print "No such file"
Feb 6 '07 #2
Sorry for not being clear on the first post. What I meant was

Script 1
---------------
./script1.py -f script2.py

To instantiate script2 , one would normally use in script1

object = script2.script2()
object.function1()

But if the name of script2 is dynamic (which comes from command line), how do I instantiate that object.


Script 2 (script2.py)
------------
Expand|Select|Wrap|Line Numbers
  1. class script2:
  2.        def __init__(self):
  3.               .........
  4.               print "In script 2 "
  5.        def function1(self):
  6.               print "Function1 "
  7.  
Thanks
Feb 6 '07 #3
bartonc
6,596 Expert 4TB
Sorry for not being clear on the first post. What I meant was

Script 1
---------------
./script1.py -f script2.py

To instantiate script2 , one would normally use in script1

object = script2.script2()
object.function1()

But if the name of script2 is dynamic (which comes from command line), how do I instantiate that object.


Script 2 (script2.py)
------------
Expand|Select|Wrap|Line Numbers
  1. class script2:
  2.        def __init__(self):
  3.               .........
  4.               print "In script 2 "
  5.        def function1(self):
  6.               print "Function1 "
  7.  
Thanks
Expand|Select|Wrap|Line Numbers
  1. __import__(filename) # leave off the .py
Feb 6 '07 #4
Thanks Barton, That helped me import the module but now how do I instantiate it or access the functions declared within that class.

Thanks
--V
Feb 6 '07 #5
Motoma
3,237 Expert 2GB
Barton! This sounds like a perfect oportunity for abstract classes! I've never done anything with python and inheritance, however, so I would appreciate your input.
Feb 6 '07 #6
Was googling around and found a way to instantiate objects on the fly.

Script 1 (Arbitrary.py)
--------------
Expand|Select|Wrap|Line Numbers
  1. import string
  2. class ArbitraryClass:
  3.         def getClass(self, moduleName):
  4.                 return __import__(
  5.                         moduleName,
  6.                         {},
  7.                         {},
  8.                         []
  9.                         )
  10.  
In your script which would instantiate other objects
Script2
------------
Expand|Select|Wrap|Line Numbers
  1. arb = Arbitrary.ArbitraryClass()
  2. instance = getattr( arb.getClass("FILENAME"), "CLASSNAME")()
  3. instance.any_function in that class 
  4.  
where FILENAME is without .py extension and CLASSNAME is the name of the class that is defined within that FILE.

Thanks
Feb 6 '07 #7
Motoma
3,237 Expert 2GB
Glad to see you've gotten it sorted out. Thanks for posting back the answer.
Feb 7 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Nischal Topno | last post by:
Hi, Is there any way to auto load/instantiate a new class of a servlet into the JVM (with shutting the web server) after replacing the old class with new one? For e.g., after a servlet is...
3
by: SammySAm | last post by:
I have a set of XSD's that I have to instantiate at run time and pass some values in C++.Net. How can I acheive it? Please advice. Best, Sam
2
by: david | last post by:
Well, as a matter of fact I_HAD_MISSED a basic thing or two, anyway, although Ollie's answer makes perfectly sense when dealing with classes, it doesn't seem to me to apply as well if you have to...
4
by: Stephen Corey | last post by:
I've got 2 classes in 2 seperate header files, but within the same namespace. If I use a line like: // This code is inside Class2's header file Class1 *newitem = new Class1(param1, param2); ...
2
by: active | last post by:
Because of an example I followed I've been instantiating Image objects. Now I notice that the documentation says the Image class is an abstract base class. Things seem to be working! Is the...
3
by: Achim Dahlhoff | last post by:
Hi. I'm trying to find out the diffrence between normal classes and classes derived from built-in types. (Which is causing me trouble trying to instantiate a class using C API calls) >>>...
2
by: Stick | last post by:
I have defined to classes like this: namespace PanelColors.Helpers { public class PanelColor { public PanelColor() { r = 0; g = 0; b = 0; }
18
by: RB | last post by:
Hi guys (and gals!), I've got 2 classes, "TypesafeConstant" and "Color". "Color" inherits from "TypesafeConstant", and adds no new functionality. All "Color" does is to instantiate some class...
2
by: sifl | last post by:
Hello All- I have always been curious about something in regards to instantiating classes, and since C++ programmers are always the experts, I am sure that you will know the answer. So, say I...
4
by: dascandy | last post by:
Hi, For a project I'm working on I'm kind-of-hacking my way around deriving a class from an interface or such to create a mock, but instead creating the mock directly. It is usable as the...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.