473,396 Members | 2,013 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,396 software developers and data experts.

How to create an object instance from a string??

How can I create an instance of an object from a string?

For example, I have a class Dog:
class Dog:
def bark(self):
print "Arf!!!"
I have a string:
classname = "Dog"

How can I create a instance of Dog from classname?
Is there any such methods like those in Java?

Jul 18 '05 #1
9 35874
Tian wrote:
I have a string:
classname = "Dog"


It's easier without strings:
classname = Dog
classname().bark() Arf!!!

Jul 18 '05 #2
On 19 Mar 2005 14:16:42 -0800, Tian <wa*********@gmail.com> wrote:
How can I create an instance of an object from a string?

For example, I have a class Dog:
class Dog:
def bark(self):
print "Arf!!!"

I have a string:
classname = "Dog"

How can I create a instance of Dog from classname?


If class Dog is in the same namespace:
dog_class = globals()[classname]
dog = dog_class()
dog.bark()

If class is declared in another file, e.g. "animals.py":
import animals
dog_class = getattr(animals, classname)
dog = dog_class()
dog.bark()
--
Ksenia
Jul 18 '05 #3
Tian wrote:
How can I create an instance of an object from a string?

For example, I have a class Dog:
class Dog:
def bark(self):
print "Arf!!!"
I have a string:
classname = "Dog"

How can I create a instance of Dog from classname?
Is there any such methods like those in Java?


You generally get a reference to the class object
(i.e. to Dog) using either globals(), locals(),
or getattr() as appropriate for the specific
situation at hand...

-Peter
Jul 18 '05 #4
This is very useful, thanks!

Jul 18 '05 #5
Hi !
Also :
classname = "Dog"
exec("b="+classname+"()")
b.bark()

or

classname = "Dog"
exec("cl="+classname)
b=cl()
b.bark()

Michel Claveau


Jul 18 '05 #6
Do Re Mi chel La Si Do wrote:
Also :
classname = "Dog"
exec("b="+classname+"()")
b.bark()

or
classname = "Dog"
exec("cl="+classname)
b=cl()
b.bark()


Ugh.

The statement exec (note: it's a statement, not a
function call as you imply with the above) is rarely
either required or good style.

In this case it's neither.

-Peter
Jul 18 '05 #7
Hi !
Sorry, but :

The statement exec does not have impact on the style.

Like with exefile or import (and other), the style is determined by the
contents. Rather judge "exec" (or import, or execfile) than the contents,
it is an error of causality.
@-salutations
--
Michel Claveau

Jul 18 '05 #8
Tian wrote:
How can I create an instance of an object from a string?

For example, I have a class Dog:

class Dog:
def bark(self):
print "Arf!!!"

def Factory(class_name):
classes = {
'Dog':Dog
}
return classes[class_name]
dog = Factory('Dog')()
--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
Jul 18 '05 #9
Hi !

Finally, it's the best solution.

Michel Claveau
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Steve Neill | last post by:
Can anyone suggest how to create an arbitrary object at runtime WITHOUT using the deprecated eval() function. The eval() method works ok (see below), but is not ideal. function Client() { }...
0
by: Patrick | last post by:
I'm working on a contact management application, and need a hand with one aspect... Here's what I want to create: ------------------------------------ A form split into two parts. There is a...
4
by: Ray | last post by:
I want to dynamically load DLLs (created from VB) and instantiate a class with a particular name, like "ProcessClass". I am able to load the DLL and confirm there is a class by that name BUT I...
2
by: John Hughes | last post by:
Hi, Is it possible to create an object from a stored (database,xml or variable) name? For instance I have 2 class names stored in my database. Depending on the application settings I want to...
2
by: Angel Of Death | last post by:
I have a method. It takes some XML as a parameter. Depending on the content of the XML it should create a specific object and call a KNOWN method. So: public void PersistXml(string XmlData){} ...
4
by: etuncer | last post by:
Hello All, I have Access 2003, and am trying to build a database for my small company. I want to be able to create a word document based on the data entered through a form. the real question is...
1
geo039
by: geo039 | last post by:
Okay I have an application, which is to demonstrate the use of a created class. I have a previous and next button which cycles through the array. However I need the user to be able to create a new...
7
by: MisterPete | last post by:
How can I inherit from file but stil create an instance that writes to stdout? ----------- I'm writing a file-like object that has verbosity options (among some other things). I know I could just...
0
by: bharathreddy | last post by:
Before going to that i want to say few thing on serialization : Serialization is the process of converting an object into a form that can be readily transported. For example, you can serialize an...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
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,...
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
Oralloy
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,...
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...
0
agi2029
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,...

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.