0

I have a function which returns a class:

def my_function():
    # some logic
    class AClass:
         def __init__(self, argument):
             init()
    return AClass

And when I call this function, it returns a class, not an object of that class, right?

Value = my_function()

My question is how can I create an object from that class AClass?

Thank you.

1
  • 1
    instance = my_function()(argument) Commented Jun 25, 2021 at 16:55

2 Answers 2

3
my_class = my_function()
my_obj = my_class(arg)
Sign up to request clarification or add additional context in comments.

Comments

1

Since the method returns a reference to a type you can simply use whatever constructor that is defined for the class directly on the return value.

Take this class for example:

class A:
    def __init_(self, n = 0):
        self.__n = n

Lets see what happens when reference the type directly when running the interpreter interactively:

>>> A
<class `__main__.A`>

Now lets return the type in a method:

>>> def f():
>>>    return A
>>> f()
<class `__main__.A`>

Since the value of referencing the class directly and when returned from a method is the same, you can use that returned value the same you would normally. Therefore a = A() is the same as a = f()(). Even if the class takes parameter you can still reference it directly: a = f()(n = 10)

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.