Difference between revisions of "Python/Definitions"
Line 34: | Line 34: | ||
square = (lambda x: x**2) | square = (lambda x: x**2) | ||
print(square(2)) | print(square(2)) | ||
>>> 4 | |||
print(square(3)) | print(square(3)) | ||
>>> 9 | >>> 9 | ||
</source> | </source> |
Revision as of 20:55, 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
- What's the difference between a method and a function? Stackoverfolow
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.
Lambda is a single line function (anonymous function)
square = (lambda x: x**2) print(square(2)) >>> 4 print(square(3)) >>> 9
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
lambda
-> keywordx
-> input argument to the anonymous function2*x*x
-> the expression to compute5
-> the function argument. Passed asx