============================================= 3: The Function Object ============================================= Summary ============= - Functions is Python are objects and can be used anywhere an object can - You can pass a function as a parameter and return a function result - Function parameters are passed by object reference, which means changes to parameters do not affect the variables used as arguments - Function s can have attributes defined which have a lifetime beyond that oof the functions local variables - Local variables exist only while the function is being executed, but attributes exist as long as the function object does - Lambda expressions are lightweight ways of creating function objects. They simplify the syntax for passing function arguments - Functions have variables which reference them rather than names - Functions can refer to their own attributes in code - A function object is an example of a callable Functions as Objects ====================== Python Function Definition ----------------------------- .. code-block:: python def sum(a,b): c = a + b return c A Way to think of a function Definition ------------------------------------------ .. code-block:: python sum = def(a,b): c = a + b return c # invalid syntax but shows that the variable "sum" is created with a reference to the new function object Function attributes --------------------- .. code-block:: python def sum(a,b): c = a + b return c #A function object has many predefined attributes that can be useful and you can add new attributes to a function object and make use of them sum.myAttribute = 1 print(sum.myAttribute) Why Functions are Objects ------------------------------ .. code-block:: python def math(f,a,b): #first parameter 'f" is a reference to a unction return f(a,b) def sum(a,b): c = a + b return c def sub(a,b): c = a - b return c print(math(sum,1,2)) print(math(sub,1,2)) Function Self Reference ------------------------- Attributes are a great way to store state information for the function This function counts the the number of times it has been used .. code-block:: python def myFunction(): myFunction.count =+ 1 myFunction.count = 0 print(myFunction.count) # zero it has not been used yet myFunction() print(myFunction.count) # 1 it has been used once etc, etc Programs ----------- I have attached 2 programs that work with functions and compliment the programs showed above .. literalinclude:: programs/passByObject.py :language: python .. literalinclude:: programs/functions.py :language: python