instantiate a class with a variable

J

John

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
 
B

Ben Finney

John said:
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::
... pass
... <__main__.Foo instance at 0x401e468c>

Or, more succinctly but rather harder to follow::
... pass
... <__main__.Foo instance at 0x401e46ec>
 
C

Cameron Laird

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

The answer is yes::

... pass
...
<__main__.Foo instance at 0x401e468c>

Or, more succinctly but rather harder to follow::

... pass
...
<__main__.Foo instance at 0x401e46ec>
.
.
.
I hope few are so unwary as not to detect the apparent typographical
error
foo_name = 'foo'
for
foo_name = 'Foo'
 
B

Ben Finney

Ben Finney said:
... pass
...

Dang. As Cameron Laird points out, this should be

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.
 
B

bruno at modulix

John said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,161
Latest member
GertrudeMa
Top