473,395 Members | 1,846 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,395 software developers and data experts.

Dynamic creation of an object instance of a class by name

Hi all

I have been searching everywhere for this, but have not found a
solution, yet.

What I need is to create an object that is an instance of a class (NOT a
class instance!) of which I only know the name as a string. This what I
tried:

class A:
def __init__(self, id):
self.id = id
def getID(self):
print self.id

ca = new.classobj('A', (), {})
oa1 = ca()
oa2 = new.instance(ca)

oa1
<__main__.A instance at 0x007E8AF8>

oa1.getID()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: A instance has no attribute 'getID'

oa2
<__main__.A instance at 0x007E8AF8>

oa2.getID()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: A instance has no attribute 'getID'
Thus, both ways only produce a class instance, but NOT an object of that
class!!! How can I get a new object instance???
What else needs to be filled in for base_classes and __dict__ in
new.classobj?
Any help is appreciated, this is driving me nuts!

kind regards
Andre
Jul 18 '05 #1
6 7722
cn = 'A'
inst = eval('%s()' % cn)

--
Regards,

Diez B. Roggisch
Jul 18 '05 #2
Andre Meyer wrote:
I have been searching everywhere for this, but have not found a
solution, yet.

What I need is to create an object that is an instance of a class (NOT a
class instance!) of which I only know the name as a string. This what I
tried:

class A:
def __init__(self, id):
self.id = id
def getID(self):
print self.id

ca = new.classobj('A', (), {})
oa1 = ca()
oa2 = new.instance(ca)

oa1
<__main__.A instance at 0x007E8AF8>

oa1.getID()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: A instance has no attribute 'getID'

oa2
<__main__.A instance at 0x007E8AF8>

oa2.getID()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: A instance has no attribute 'getID'
Thus, both ways only produce a class instance, but NOT an object of that
class!!! How can I get a new object instance???
What else needs to be filled in for base_classes and __dict__ in
new.classobj?
Any help is appreciated, this is driving me nuts!

kind regards
Andre


Don't listen to the voices whispering "Use eval()" or "globals() are the way
to go", make it clean and explicit with a dictionary containing all classes
you want to expose:
class A: pass .... class B: pass .... class C: pass .... exposed = dict(A=A, B=B, C=C)
exposed["A"]()


:-)

Peter

Jul 18 '05 #3
> Don't listen to the voices whispering "Use eval()" or "globals() are the
way to go", make it clean and explicit with a dictionary containing all
classes you want to expose:


Out of curiosity - why not to use eval? having a dict like yours makes
things look like your average java factory pattern - some explicit
structure, to which access has to be guaranteed and that requires a
registration.

Of course, if you know that you will always only select the class from a
fixed num of classes, your approach ensures that no non-compliant classes
can be selected - but hey, we're dynamic here ;) You never can be totally
sure what you get....
--
Regards,

Diez B. Roggisch
Jul 18 '05 #4
me***@acm.org (Andre Meyer) writes:
Hi all

I have been searching everywhere for this, but have not found a
solution, yet.

What I need is to create an object that is an instance of a class (NOT a
class instance!)
I'm sorry, I can't for the life of me figure out what the (semantic)
difference is between "intsance of a class" and "class instance".
of which I only know the name as a string. This what I
tried:

class A:
def __init__(self, id):
self.id = id
def getID(self):
print self.id

ca = new.classobj('A', (), {})
This creates a new class which will be called "A", displacing your
original class by the same name.
oa1 = ca()
oa2 = new.instance(ca)

oa1
<__main__.A instance at 0x007E8AF8>

oa1.getID()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: A instance has no attribute 'getID'

oa2
<__main__.A instance at 0x007E8AF8>

oa2.getID()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: A instance has no attribute 'getID'
Thus, both ways only produce a class instance, but NOT an object of that
class!!!
Yes, they produce an instance of your newly created class.
How can I get a new object instance???
I think you mean to ask "How can I get a new instance of the class
whose name I have in a string?". In other words, you should be asking
yourself, "How can I get my hands on an object whose name[*] I have in a
string?" (One possible approach is shown below.)
What else needs to be filled in for base_classes and __dict__ in
new.classobj?


You can't do it that way ... that way you create a _new_ separate
class called "A".

Here's how you might achieve what you want:
class A: .... def __init__(self, id):
.... self.id = id
.... def getID(self):
.... print self.id
.... oa1 = globals()['A'](12345)
oa1 <__main__.A instance at 0x8190844> oa1.getID() 12345
[*] I'm a bit wary about using "name" here, because I don't really
mean the name of the class, but the name of a variable that
happens to refer to the class.

For example, consider (in the context established above)
B = A
del A
B.__name__ 'A' A.__name__

Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'A' is not defined

So, while the name of the class is still "A", it is no longer
known by an identifier of that name.
Jul 18 '05 #5
Diez B. Roggisch wrote:
Don't listen to the voices whispering "Use eval()" or "globals() are the
way to go", make it clean and explicit with a dictionary containing all
classes you want to expose:


Out of curiosity - why not to use eval? having a dict like yours makes
things look like your average java factory pattern - some explicit
structure, to which access has to be guaranteed and that requires a
registration.

Of course, if you know that you will always only select the class from a
fixed num of classes, your approach ensures that no non-compliant classes
can be selected - but hey, we're dynamic here ;) You never can be totally
sure what you get....


It's probably a matter of taste, but most of the time the use of eval()
suggests more freedom than there actually is. Let's suppose there are 3
classes A, B, and C that will be used by your eval(), that limitation may
then be enforced in various parts of your code or in the documentation,
while I tend to see exposed = dict(...) as self-documenting. You can go to
the implementation of one class in the list to look up the interface.

To take an (almost) real-world example from the library, what would you
suppose the following to do?

klass = eval(klass, vars(logging))

What would you do to make the above accept your special-purpose handler
class? I think something like

availableHandlers = {...}

def registerHandler(name, klass, replace=False):
if not replace and name in availableHandlers:
raise NameClash
availableHandlers[name] = klass

formatterClass = availableHandlers[name]

is much clearer.

As a side note (not that I think this is important here), eval() is not the
fastest of functions:

$ timeit.py -s"class A: pass" -s"all=dict(A=A)" "all['A']"
10000000 loops, best of 3: 0.147 usec per loop
$ timeit.py -s"class A: pass" "eval('A')"
10000 loops, best of 3: 19.7 usec per loop
Peter

Jul 18 '05 #6
Right, ok, well, I do not assume to know what classes can be instantiated, thus
anything like accessing globals() is not likely to help, sorry. The eval()
version works pretty ok so far. I am develpoing a module of which other people
can make use of by developing their own subclasses, but they need to be
instantiated by my code. Eval() does the trick for me or is there a better way,
assuming you do not need to know which class it might be beforehand?
btw I LOVE dynamicity... ;-)

kind regards
Andre
Jul 18 '05 #7

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

Similar topics

16
by: 4Space | last post by:
I've hit something of a snag. Problem: In a DSP application we have data profiles with a varying number of points. We have a number of Discrete Fourier transforms that are optimised for a...
0
by: Pascal Costanza | last post by:
Dynamic Languages Day @ Vrije Universiteit Brussel ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Monday, February 13, 2006, VUB Campus Etterbeek The VUB (Programming Technology Lab,...
5
by: Russell Warren | last post by:
I just ran across a case which seems like an odd exception to either what I understand as the "normal" variable lookup scheme in an instance/object heirarchy, or to the rules regarding variable...
2
by: Luis Arvayo | last post by:
Hi, In c#, I need to dynamically create types at runtime that will consist of the following: - inherits from a given interface - will have a constructor with an int argument
13
by: DaTurk | last post by:
Hi, This is a question brought about by a solution I came up with to another question I had, which was "Dynamic object creation". So, I'm curious if you can dynamically cast an object. If you...
16
by: manatlan | last post by:
I've got an instance of a class, ex : b=gtk.Button() I'd like to add methods and attributes to my instance "b". I know it's possible by hacking "b" with setattr() methods. But i'd like to do...
23
by: Frank Millman | last post by:
Hi all I have a small problem. I have come up with a solution, but I don't know if it is a) safe, and b) optimal. I have a class with a number of attributes, but for various reasons I cannot...
0
by: daylond | last post by:
I'm developing a robot control architecture, and am trying to maximize platform independence (robot hardware, not OS) by generating my individual behaviors as dynamic libraries. The individual...
12
by: andrew cooke | last post by:
Hi, This is my first attempt at new classes and dynamic python, so I am probably doing something very stupid... After reading the how-to for descriptors at...
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
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:
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
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...
0
tracyyun
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...

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.