Difference between revisions of "Python/Definitions"

From Ever changing code
Jump to navigation Jump to search
Line 55: Line 55:
|-  
|-  
! Lambda
! Lambda
! <code>def</code> full function
! <code>def</code> named function
|- style="vertical-align:top;"
|- style="vertical-align:top;"
| <source lang=python>func_lambda = lambda x: x*10
| <source lang=python>func_lambda = lambda x: x*10

Revision as of 21:33, 21 March 2020

Function vs Method

method is the object-oriented word for function, no real difference. So, the split is:

  • method is on an object.
  • function is independent of an object.


A function
is a piece of code that is called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.
A method
is a piece of code that is called by a name that is associated with an object. A method is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).


All because of a class

Look the code below. A class called Door which has a method(action) called open. There is another portion of code with def just below which defines a function, it is a function because it is not declared inside a class, this function calls the method we defined inside our class as you can see and finally the function is being called by itself.

class Door:
  def open(self):  # <- method
    print 'hello'

def knock_door:    # <- function
  a_door = Door()
  Door.open(a_door)

knock_door()


References

Lambda function

Is most commonly used when passing a simple function as an argument to another function. The syntax consists of the lambda keyword followed by a list of arguments, a colon, and the expression to evaluate and return.


In comparison, creating a function normally (using def) assigns it to a variable automatically. In the function below value of the calculation will be assigned to my_func variable.

def my_func():
  return "Hello" # <- it's 'return' statement that assigns value to 'my_func' variable

print(my_func()) # <- this prints 'my_func' variable it has just function syntax()
>>> Hello


Lambda is a single line function (anonymous function/unnamed function)

square = (lambda x: x**2)
print(square(2))
>>> 4
print(square(3))
>>> 9


Comparison Lambda vs Named def full function
Lambda def named function
func_lambda = lambda x: x*10
print(func_lambda("Hi")) 
>>> HiHiHiHiHiHiHiHiHiHi
def func_full(x):
    return x*10
print(func_full("Hi"))
>>> HiHiHiHiHiHiHiHiHiHi


Lambda passed as an argument to another function

def my_func(f, arg):
  return f(arg)

my_func(lambda x: 2*x*x, 5)
>>> 50
  1. lambda -> keyword
  2. x -> input argument to the anonymous function
  3. 2*x*x -> the expression to compute
  4. 5 -> the function argument. Passed as x