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 methodazro– azro2020年04月02日 08:20:46 +00:00Commented Apr 2, 2020 at 8:20
-
1The class is redefined every time you call the function. You can't easily access the class from outside the function.L3viathan– L3viathan2020年04月02日 08:21:53 +00:00Commented 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.Konrad Rudolph– Konrad Rudolph2020年04月02日 08:22:11 +00:00Commented 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.juanpa.arrivillaga– juanpa.arrivillaga2020年04月02日 08:22:52 +00:00Commented Apr 2, 2020 at 8:22
2 Answers 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
Tin Nguyen
5,3801 gold badge16 silver badges34 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
Rafaël Dera
4193 silver badges10 bronze badges
Comments
lang-py