04b - Function and Class Basics#
Functions are used all the time and are a way to organize code. They are an efficient way to use the computer to repeat calculations with slight variations. Multiple examples are given here of functions you’ll use in your educational and professional career.
Functions are defined with the def
keyword. The function name is followed by parentheses and a colon. The code block that follows is indented. The function is called by its name followed by parentheses. The function can return a value with the return
keyword. If no return value is specified, the function returns None
.
Simple Function Examples#
First, a simple function definition with a single parameter to return the sum of 2 plus some number
def add_two(num):
return 2 + num
print(add_two(5))
#or
print(f'The sum of 5 and two is {add_two(5)}') # this is better than the first print statement as it is more readable
7
The sum of 5 and two is 7
How about a function that instead of returning a value, prints the result.
How about a function that has a default value for a parameter. Or can you rewrite the first example with a default value for the parameter?
How about a function that takes in an argument that could be a list or tuple and returns the sum of the elements in the list or tuple? The function should use a loop to iterate over the elements in the list or tuple.
What about if the function is called with something other than a number in the list or tuple? How can you handle that?
Class Basics#
A class is a way to structure code. Object oriented code is very prevalent and it makes code easier to read and understand. A class is defined with the class
keyword. The class name is followed by parentheses and a colon. The code block that follows is indented. The class is instantiated by calling the class name followed by parentheses. The class can have a constructor method that is called when the class is instantiated. The constructor method is defined with the def
keyword and the method name __init__
. The constructor method can take parameters. The class can have other methods that are called with the class instance followed by a period and the method name. The class can have attributes that are accessed with the class instance followed by a period and the attribute name.
In this class we won’t worry about the init method, we’ll use the params package to handle that. We’ll just focus on the basics of a class.
Simple Class Examples#
Lets make a jar class that has a single property of its size in liters.
First import the params package and then define the class.
import param
class jar(param.Parameterized):
size = param.Number(5, bounds=(0, 100), doc='Size of the jar in liters') #default value is 5 liters and the bounds are between 0 and 100 liters
Now lets instantiate the class and access the attribute. The instantiated item is called an instance or an object of that class. In this case, lets call the instance of the class a variable called blue_jar that has a size of 10 liters.
blue_jar = jar(size=10)
help(blue_jar)
Help on jar in module __main__ object:
class jar(param.parameterized.Parameterized)
| jar(**params)
|
| params(size=Number, name=String)
| Parameters of 'jar'
| ===================
|
| Parameters changed from their default values are marked in red.
| Soft bound values are marked in cyan.
| C/V= Constant/Variable, RO/RW = ReadOnly/ReadWrite, AN=Allow None
|
| Name Value Type Bounds Mode
|
| size 5 Number (0, 100) V RW
|
| Parameter docstrings:
| =====================
|
| size: Size of the jar in liters
|
| Method resolution order:
| jar
| param.parameterized.Parameterized
| builtins.object
|
| Data and other attributes defined here:
|
| name = 'jar'
|
| size = 5
|
| ----------------------------------------------------------------------
| Methods inherited from param.parameterized.Parameterized:
|
| __getstate__(self)
| Save the object's state: return a dictionary that is a shallow
| copy of the object's __dict__ and that also includes the
| object's __slots__ (if it has any).
|
| __init__(self, **params)
| Initialize self. See help(type(self)) for accurate signature.
|
| __repr__ = wrapper(self, *args, **kwargs)
|
| __setstate__(self, state)
| Restore objects from the state dictionary to this object.
|
| During this process the object is considered uninitialized.
|
| __str__(self)
| Return a short representation of the name and class of this object.
|
| debug = inner(*args, **kwargs)
| Inspect .param.debug method for the full docstring
|
| defaults = inner(*args, **kwargs)
| Inspect .param.defaults method for the full docstring
|
| message = inner(*args, **kwargs)
| Inspect .param.message method for the full docstring
|
| pprint = wrapper(self, *args, **kwargs)
|
| print_param_values = inner(*args, **kwargs)
| Inspect .param.print_param_values method for the full docstring
|
| script_repr(self, imports=[], prefix=' ')
| Deprecated variant of __repr__ designed for generating a runnable script.
|
| state_pop(self)
| Restore the most recently saved state.
|
| See state_push() for more details.
|
| state_push(self)
| Save this instance's state.
|
| For Parameterized instances, this includes the state of
| dynamically generated values.
|
| Subclasses that maintain short-term state should additionally
| save and restore that state using state_push() and
| state_pop().
|
| Generally, this method is used by operations that need to test
| something without permanently altering the objects' state.
|
| verbose = inner(*args, **kwargs)
| Inspect .param.verbose method for the full docstring
|
| warning = inner(*args, **kwargs)
| Inspect .param.warning method for the full docstring
|
| ----------------------------------------------------------------------
| Class methods inherited from param.parameterized.Parameterized:
|
| print_param_defaults = inner(*args, **kwargs) from param.parameterized.ParameterizedMetaclass
| Inspect .param.print_param_defaults method for the full docstring
|
| set_default = inner(*args, **kwargs) from param.parameterized.ParameterizedMetaclass
| Inspect .param.set_default method for the full docstring
|
| ----------------------------------------------------------------------
| Readonly properties inherited from param.parameterized.Parameterized:
|
| param
|
| ----------------------------------------------------------------------
| Data descriptors inherited from param.parameterized.Parameterized:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from param.parameterized.Parameterized:
|
| force_new_dynamic_value = functools.partial(<function Parameters.depre...
| Inspect .param.force_new_dynamic_value method for the full docstring
|
|
| get_param_values = functools.partial(<function Parameters.deprecate......
| Inspect .param.get_param_values method for the full docstring
|
|
| get_value_generator = functools.partial(<function Parameters.deprecate...
| Inspect .param.get_value_generator method for the full docstring
|
|
| inspect_value = functools.partial(<function Parameters.deprecate...s>....
| Inspect .param.inspect_value method for the full docstring
|
|
| params = functools.partial(<function Parameters.deprecate...s>.inner a...
| Inspect .param.params method for the full docstring
|
|
| set_dynamic_time_fn = functools.partial(<function Parameters.deprecate...
| Inspect .param.set_dynamic_time_fn method for the full docstring
|
|
| set_param = functools.partial(<function Parameters.deprecate...s>.inne...
| Inspect .param.set_param method for the full docstring
Lets add another parameters to the jar class that is how much is in the jar. That parameter we will call “amount”.
Lets also add a method to the class that adds to the amount in the jar by any specific amount.