0

mabe I'm asking for too much, but, is there possibility to create variable for instantiating class with name from another string variable?

something like this:

 name = 'my_class_instance' # string variable holding name

 my_class_instance = my_cool_class(arg1, arg2, arg3)  #instance of a class in variable with name from string

br, Ivica

1
  • 1
    Possible? yes. But unless you have a very good reason to do so, it's a bad idea. Most cases where someone thinks they need dynamically named variables are better served by using the right data types such as dictionaries. Commented Feb 24, 2021 at 12:23

1 Answer 1

1

First of all, I have to say it is very-very dangerous and not recommended to do that.

But you can do it with exec function. You can find more info about it on this page.

I have written a representative code for you.

Code:

name = "my_class_instance"


class MyCoolClass(object):
    def __init__(self, arg1, arg2, arg3):
        self.arg1 = arg1
        self.arg2 = arg2
        self.arg3 = arg3

    def print_args(self):
        print(self.arg1)
        print(self.arg2)
        print(self.arg3)


exec(
    "{var_name} = MyCoolClass({arg1}, {arg2}, {arg3})".format(
        var_name=name, arg1="'test_1'", arg2="'test_2'", arg3="'test_3'"
    )
)

my_class_instance.print_args()

Output:

>>> python3 test.py
test_1
test_2
test_3
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.