finomamonster
finomamonster

Reputation: 111

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.

Upvotes: 0

Views: 1623

Answers (2)

Mahrez BenHamad
Mahrez BenHamad

Reputation: 2068

We need to clarify some points:

  1. To call/invoke a class/function in the major of programming languages you have to use parentheses

  2. The class/function name simply refers to its object in the memory, therefore without using parentheses we actually referring to the class/function object

  3. When we use parentheses we actually call/invoke the class/function code and code got executed

Upvotes: 0

Rodney
Rodney

Reputation: 3041

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.

Upvotes: 3

Related Questions