pythonclassinstantiation

Why do I need parentheses when instantiating a class?


class Human:
    def exist(self)
        return print("exists")

H1 = Human # Why do I need parentheses here? I get error if i dont put parentheses here.

H1.exist() # I get an error that says parameter 'self' unfilled.

The class Human does not take any arguments, there isn't even an __init__ method. If I can't give any arguments when making an instance of Human, then why do I need parentheses there?

I don't even know what I don't understand but I feel like I am missing something. Probably something about self.


Solution

  • In languages where the calling of a function/method/macro takes the form

    foo(param1, param2, param3)
    

    then it is almost universally true that, if foo were to take no parameters, the call would be

    foo()
    

    and further that, depending on the language

    foo
    

    is either incorrect, or means something else.

    Now lets consider your example, expanded a bit

    H1 = Human
    H2 = Human
    H3 = Human
    

    In this case, nothing was called. H1, H2 and H3 have all been assigned the same reference, which is a reference to the class Human and not to any instance of that class.

    H1 = Human()
    H2 = Human()
    H3 = Human()
    

    In this case, the class was instantiated 3 times, that means that the __init__ function was run 3 sepearate times, and the result of each is a different instance of Human. H1, H2 and H3 now point to three different objects, all instances of Human. Since they are instances, they have a self.