Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Class in function

def creator():
    class MyClass:
        def __init__(self):
            print('__init__ of MyClass')

    print('before creating instance')
    o = MyClass()
    print(o)
    print(o.__class__.__name__)

creator()

# before creating instance
# __init_ of MyClass
# <__main__.creator.<locals>.MyClass object at 0x7fa4d8d581c0>
# MyClass

# Cannot use it outside of the function:
# MyClass()  # NameError: name 'MyClass' is not defined