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?

asked Apr 2, 2020 at 8:20
4
  • You can call it only from inside the method Commented Apr 2, 2020 at 8:20
  • 1
    The class is redefined every time you call the function. You can't easily access the class from outside the function. Commented Apr 2, 2020 at 8: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. Commented Apr 2, 2020 at 8: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. Commented Apr 2, 2020 at 8:22

2 Answers 2

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.

answered Apr 2, 2020 at 8:29
Sign up to request clarification or add additional context in comments.

Comments

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").

answered Apr 2, 2020 at 8:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.