简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM