Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of calling function without brackets python

Tags:

Consider the following:

class objectTest():      def __init__(self, a):         self.value = a      def get_value(self):         return self.value  class execute():      def __init__(self):         a = objectTest(1)         b = objectTest(1)                  print(a == b)         print(a.get_value() == b.get_value)         print(a.get_value() == b.get_value())         print(a.get_value == b.get_value)  if __name__ == '__main__':     execute = execute() 

This code return

>>> False False True  False 

Given that get_value is a function, I would expect the execution to stop and return an error, but it doesn't. Can somebody explain why the python interpreter allow this kind of syntax instead of raising an attribute error, which in my case would have saved me precious time.

like image 565
user3311142 Avatar asked Feb 14 '14 17:02

user3311142


People also ask

What is the purpose of calling a function in Python?

Functions can be called anywhere and the number of times in a program. It allows us to reuse the code by simply calling the particular function or block in a program. Thus, it avoids the repetition of the same code.

Why do we use brackets in Python?

[] (Index brackets) Index brackets ([]) have many uses in Python. First, they are used to define "list literals," allowing you to declare a list and its contents in your program. Index brackets are also used to write expressions that evaluate to a single item within a list, or a single character in a string.

How do you call a function without an argument in Python?

Defining a Function Without Parameters We can call the function by typing its name followed by parentheses () . When we call this function, it will print the current date. Note that, this output can be different for you. The output will be the date in which you call the function.

What does an empty bracket mean in Python?

This is to indicate that you have an empty "list" as opposed to any variables. It also allows you to invoke specific methods like . append used in your code for subst_words.


2 Answers

As mentioned, functions and methods are first-class objects. You call them by throwing some parentheses (brackets) on the end. But it looks like you want some more motivation for why python even lets us do that. Why should we care if functions are first-class or not?

Sometimes you don't want to call them, you want to pass a reference to the callable itself.

from multiprocessing import Process t = Process(target=my_long_running_function) 

If you put brackets after the above, it runs your my_long_running_function in your main thread; hardly what you wanted! You wanted to give Process a reference to your callable that it will run itself in a new process.

Sometimes you just want to specify the callable and let something else...

def do_something(s):     return s[::-1].upper()  map(do_something,['hey','what up','yo']) Out[3]: ['YEH', 'PU TAHW', 'OY'] 

(map in this case) fill in its arguments.

Maybe you just want to drop a bunch of callables into some collection, and fetch the one you want in a dynamic manner.

from operator import *  str_ops = {'<':lt,'>':gt,'==':eq} # etc op = str_ops.get(my_operator) if op:     result = op(lhs,rhs) 

The above is one way to map string representations of operators onto their actual action.

like image 137
roippi Avatar answered Oct 12 '22 14:10

roippi


Functions and methods in Python are also objects themselves. Thus you can compare them just as you would any other object.

>>> type(a.get_value) <type 'instancemethod'> >>> type(a.get_value()) <type 'int'> 

Normally of course you wouldn't compare methods to each other or anything else, because it's not terribly useful. One place it's useful is when you want to pass a function into another function.

like image 27
Mark Ransom Avatar answered Oct 12 '22 15:10

Mark Ransom