Abdelrahman_Mostafa
Abdelrahman_Mostafa

Reputation: 25

Calling a class that is inside a function

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?

Upvotes: 0

Views: 68

Answers (2)

Rafaël Dera
Rafaël Dera

Reputation: 409

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

Upvotes: 0

Tin Nguyen
Tin Nguyen

Reputation: 5330

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.

Upvotes: 2

Related Questions