Python: What is the difference between calling a method with () and without?

StackOverflow https://stackoverflow.com/questions/22326622

  •  12-06-2023
  •  | 
  •  

سؤال

It must be something very basic and obvious, because I just can't find the answer through google or on here...

What difference do the parentheses make in Python when I call methods?

Example code with pygame and parentheses:

import pygame
import sys

pygame.init()

screen = pygame.display.set_mode((640, 480))

running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()

When I click the cross of the window, it closes with sys.exit() being the last thing called in the Traceback.

When I change it to this:

import pygame
import sys

pygame.init()

screen = pygame.display.set_mode((640, 480))

running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit

    pygame.display.update()

It still quits but with a display error as last item in the Traceback.

I came across this when I followed this tutorial for Panda3D here: http://www.mygamefast.com/volume1/

In several of the issues (e.g. here in the "keyboardSetup" method of the "ArcadeFlightGame" class: http://www.mygamefast.com/volume1/issue5/4/) he calls "sys.exit" instead of "sys.exit()" and the game terminates correctly. If I change it to "sys.exit()" it causes some error when starting.

This seems to be so very basic that nobody really explained it anywhere... I would really appreciate it if somebody could enlighten me a little on this :/

هل كانت مفيدة؟

المحلول

If you don't use parenthesis, you aren't calling the function. It's just that simple. sys.exit does absolutely nothing, sys.exit() calls the function.

That being said, sometimes the name of a function without parenthesis will be passed to some other function, or bound to an event. In such a case, parenthesis aren't used because you are telling this other function or event "call this at the appropriate time".

For example, in the tutorial you linked to is this line of code:

self.accept("escape", sys.exit)

This is not calling sys.exit. Instead, it is telling the event system "when you detect the escape key, call this function". At the time this code is called, sys.exit is not called, but rather registered to be called later. When the escape key is pressed, the underlying framework will actually call the function using parenthesis.

So, there is a difference between immediately calling a function (using ()) and registering a function (using the name only, no ()).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top