0

Would it be possible to call a class that is inside of a function?

Example:

def func():
  class testclass:
    print("testclass")

How would i call testclass in a position like this?

  • You can call it only from inside the method – azro Apr 02 '20 at 08:20
  • 1
    The class is redefined every time you call the function. You can't easily access the class from outside the function. – L3viathan Apr 02 '20 at 08:21
  • You can’t “call” a class. in the code you’ve shown you’re *defining* a class, and when you create objects from it you are *instantiating* it. – Konrad Rudolph Apr 02 '20 at 08:22
  • The same way you use *any* object created inside a function, you return it from the function and it is up to the caller to use the object. – juanpa.arrivillaga Apr 02 '20 at 08:22

2 Answers2

2
def mymethod(value):
    class TestClass:
        def __init__(self, a):
            self.a = a
    t = TestClass(value)
    print(f"Inside method printing a value {t.a}")
    return t

test = mymethod(5)
print(f"Outside method printing object's value {test.a}")

Possible.

Tin Nguyen
  • 5,250
  • 1
  • 12
  • 32
0

Of course you can do this; however python has several ways to build classes with different characteristics. Some strategies you may want to look into include inheritance or "mixins" and/or to have several constructor methods like in this answer: https://stackoverflow.com/a/682545/6019407

I think this approach is generally considered more in keeping with the python style ("pythonic").

Rafaël Dera
  • 399
  • 2
  • 9