473,480 Members | 1,874 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

instantiate a class with a variable

Hi, is it possible to instantiate a class with a variable.

example

class foo:
def method(self):
pass

x='foo'

Can I use variable x value to create an instance of my class?

Thanks, John

Mar 27 '06 #1
5 1826
"John" <jo***************@yahoo.com> writes:
class foo:
def method(self):
pass

x='foo'

Can I use variable x value to create an instance of my class?


You seem to be asking "is it possible to call an object whose name is
stored in a string".

The answer is yes::
class Foo: ... pass
... foo_name = 'foo'
foo_class = locals().get(foo_name)
bar = foo_class()
bar <__main__.Foo instance at 0x401e468c>

Or, more succinctly but rather harder to follow::
class Foo: ... pass
... foo_name = 'foo'
bar = locals().get(foo_name)()
bar

<__main__.Foo instance at 0x401e46ec>

--
\ "I went to the cinema, it said 'Adults: $5.00, Children $2.50'. |
`\ So I said 'Give me two boys and a girl.'" -- Steven Wright |
_o__) |
Ben Finney

Mar 28 '06 #2
In article <ma***************************************@python. org>,
Ben Finney <bi****************@benfinney.id.au> wrote:
"John" <jo***************@yahoo.com> writes:
class foo:
def method(self):
pass

x='foo'

Can I use variable x value to create an instance of my class?


You seem to be asking "is it possible to call an object whose name is
stored in a string".

The answer is yes::
>>> class Foo: ... pass
... >>> foo_name = 'foo'
>>> foo_class = locals().get(foo_name)
>>> bar = foo_class()
>>> bar <__main__.Foo instance at 0x401e468c>

Or, more succinctly but rather harder to follow::
>>> class Foo: ... pass
... >>> foo_name = 'foo'
>>> bar = locals().get(foo_name)()
>>> bar

<__main__.Foo instance at 0x401e46ec>

Mar 28 '06 #3
Ben Finney <bi****************@benfinney.id.au> writes:
>>> class Foo: ... pass
... >>> foo_name = 'foo'
Dang. As Cameron Laird points out, this should be
foo_name = 'Foo'


each time.

Moral of the story: if the example already works, and then you cut and
paste into the message compose window, and then notice that it could
be clearer and edit it some more...

.... always test the example code you're *actually* presenting, after
all edits.

--
\ "You know what would make a good story? Something about a clown |
`\ who makes people happy, but inside he's real sad. Also, he has |
_o__) severe diarrhea." -- Jack Handey |
Ben Finney

Mar 28 '06 #4
John wrote:
Hi, is it possible to instantiate a class with a variable.

example

class foo:
def method(self):
pass

x='foo'

Can I use variable x value to create an instance of my class?


You got examples using string 'foo', now if all you need is to store or
pass around the class, just use it as any other object (yes, classes
*are* objects):

class Foo(object): pass

x = Foo

f = x()
assert type(f) is Foo
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Mar 28 '06 #5
Thanks for the help, this was exactly what I needed. Working Great
bruno at modulix wrote:
John wrote:
Hi, is it possible to instantiate a class with a variable.

example

class foo:
def method(self):
pass

x='foo'

Can I use variable x value to create an instance of my class?


You got examples using string 'foo', now if all you need is to store or
pass around the class, just use it as any other object (yes, classes
*are* objects):

class Foo(object): pass

x = Foo

f = x()
assert type(f) is Foo
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"


Mar 28 '06 #6

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

Similar topics

2
4707
by: Colin Mc Mahon | last post by:
Hi all, I currently use a class to interface with my databases, allowing me to insert, update, delete and retrieve records from the database as methods of the class. I have now created a...
5
2351
by: Glenn Serpas | last post by:
I have Class A and Class B .. Class B has a private member that is a pointer to a Class A object. private: B *mypointer ; I instantiate the A object A* myobject new = A();
6
2442
by: Jason Shohet | last post by:
2 questions for anyone who can answer: 1. in class declarations, I realize you have to use the NEW keyword if you want to declare & instantiate some class at the same time. Whats an advantage...
7
1972
by: J-T | last post by:
I can instantiate my object in my *ASP.NET* application in two ways: A) public sealed class RSSingleton { private static ReportingServiceProxy m_RsProxy=null; static RSSingleton() {...
1
998
by: Dean Slindee | last post by:
If a string variable contains a value that is the name of a class, is there any way to instantiate the class from the contents? Example: Dim strClassName as String = "Foo" Dim cls as New...
1
1611
by: Donald Westfield | last post by:
I have my own module, called mystuff.py, which is to be imported for an app. The number of classes in the module will vary, so I need a subroutine that will instantiate all of them as objects,...
2
3278
by: Merk | last post by:
I'm wanting to know if/how it would be possible to load a form based on a string that contains the name of the form (class). For example, instead of doing this: myForm f = new myForm();...
2
1321
by: Pyenos | last post by:
class model:pass class view: model() class controller: model() I can instantiate clsss model from inside class view but I can't instantiate class model from inside controller, due to the...
4
2066
by: Arne-Kolja Bachstein | last post by:
Hi there, I am planning to implement a plugin system, based on the observer pattern in some way, but now I am stuck with the instantiation of the plugins. I want the plugins to have their own...
0
7041
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
7043
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
7081
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...
1
6737
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
5336
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,...
0
4481
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...
0
2984
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
563
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
179
bsmnconsultancy
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...

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.