-2

To meet the specifications of a program I'm writing I need to be able to generate an instance of a class on the fly that can be referenced easily by other parts of the code.

I've looked around and can't find an answer to this, can I do this within python or not?

Thank you to all replies in advanced.

5
  • 3
    Yes, this can be done. Commented May 16, 2017 at 23:27
  • Possible duplicate of Creating an Instance of a Class with a variable in Python Commented May 16, 2017 at 23:27
  • uh my_instance = MyClass()? Commented May 16, 2017 at 23:31
  • This is very vague. What do you mean by "on the fly"? What do you mean by "referenced easily"? Commented May 16, 2017 at 23:51
  • I think you are asking for some type of dynamic instantiation. Metaclasses may be an option. Supply some code and someone will be able to directly assist you. Commented May 17, 2017 at 0:59

1 Answer 1

1

Yes, it's possible.

For example you could create an instance and return it from a function:

def some_function():
    some_instance = int('10')
    return some_instance

a = some_function()   # returns an instance and store it under the name "a"
print(a + 10)  # 20

You could also use global (I wouldn't recommend it though):

a = None

def some_other_function():
    # tell the function that you intend to alter the global variable "a",
    # not a local variable "a"
    global a   
    a = int('10')

some_other_function()  # changes the global variable "a"
print(a)   # 10
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.