Is it a general concept to have methods written in the code without brackets? For example in tkinter yview in ttk.Scrollbar(window, orient = "vertical", command = window.yview), set in canvas.configure(yscrollcommand = scrollbar.set), or
self-defined square in
def square(x):
return x * x
numbers = [1, 2, 3, 4]
print(map(square, numbers))
Sure. In Python, everything is an object, including functions (and methods). As such, you can pass a function to another function as an argument, just as you could with any other object.
But window in ttk.Scrollbar(window, orient = "vertical", command = window.yview) is not a function, rather a widget. Or does it mean, that I am sending only the yview in the scope of the window widget to some hidden function, which operates the command attribute?
That’s it. Anything that you can name (function, class, class instance, constant…), you can also send as argument in a function call. Here ttk.Scrollbar(...) is essentially also a function call (it calls the Scrollbar.__init__ function to initialize the Scrollbar instance - does a bit more than just this, but that’s not really relevant here).
If you look at map then you could re-implement that (less efficiently) as:
def mymap(func, container):
return [func(x) for x in container]
Tkinter chooses when and how to call the provided command, according to its own logic. You provided window.yview, which can be called. Here, it doesn’t matter what window is, because that’s not what the command is - the command is window.yview, i.e. a method of the window.
When you write x( and then some arguments and then ), you are “calling” x. Even if x isn’t an ordinary function (methods and classes can be called; instances of a class can be made callable if they have a special __call__ method; and you can try to call anything, it just won’t always work). Even if x isn’t just a name for something, but a whole other expression. For example, if a class defined __call__, and made that method return another instance of the class, then those instances could be called repeatedly:
class Example:
def __init__(self):
print(self, "was created")
def __call__(self):
print(self, "was called")
return Example() # also try it with `return self` instead
Example()()()()()()()()