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

旧巷老猫 提交于 2019-12-01 06:34:08

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 ()).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!