Search code examples
pythoninitpython-3.9python-class

what's the difference between those two similar __init__ definitions in python?


what's the difference between

1)

def __init__(self): pass

and

2)

def __init__(self) -> None: pass

thank you for your help!


Solution

  • In second one, you annotated the method and explicitly said that the return value of the __init__ method should be None.

    Every function/method in Python will implicitly return None if you don't have any return statement in the body. It is necessary for __init__ to return None, otherwise you will get the error TypeError: __init__() should return None, in instantiation.

    Annotation is optional and won't throw an error if you put different value from the specified one:

    def fn() -> str:
        return 10
    
    print(fn())  # 10
    

    But returning None is a must for __init__.

    class A:
        def __init__(self):
            return 10
    
    obj = A()  # TypeError: __init__() should return None, not 'int'