Function and Class
◤
What is function
◤
The structure of function
◤
Without return
Actually, the function return None.
◤
The parameters of the function
◤
◤
Keyword argument
◤
Default argument
The default arguments need to
be placed after the non-default
arguments
◤
Exercise
Control | |
Gene ID | Expression |
G1021 | 1102 |
G1031 | 3102 |
G1032 | 403 |
G0143 | 423 |
G3923 | 119 |
G1203 | 3952 |
Covid | |
Gene ID | Expression |
G1021 | 102 |
G1031 | 3121 |
G1032 | 3403 |
G0143 | 398 |
G3923 | 134 |
G1203 | 4005 |
◤
Using function
◤
*args, **kwargs
◤
tuple
◤
Use for loop to rewrite the script
◤
Shortages of using *args
◤
**kwargs as a dict
dict
◤
Exercise
List name | | | | | | | |
Biochemistry | 70 | 87 | 67 | 99 | 94 | 84 | 67 |
Programming | 90 | 93 | 89 | 83 | 90 | 93 | 81 |
Anatomy | 87 | 67 | 72 | 79 | 90 | 76 | 88 |
◤
◤
Local variables and global variables
a = 1
a = 1
a = 1
b = 2
b = None
b = None
◤
a is a global variable
b is a local variable
How can we make b recognizable outside of the function?
Using assigned parameters to functions and
return from the functions can assist the transfer
of variables.
◤
Called by value and called by reference
◤
3 | “ttt” | 345.21 | None | False | “OK” |
Input += 3
a
s
value
detect
ans
The original a is not changed.
Called
by
value
3 | “ttt” | 345.21 | None | False | “OK” |
a = [
]
index
Variable name
0
1
2
3
4
5
def function(input)
def function(input)
Input[0] += 3
The original a is changed.
Called
by
reference
Normally, the variable with single value belongs to called by value. List, dict and tuple belong to called by reference.
But if the whole list, dict or tuple are reassigned. It also belongs to called by value
◤
Called by value
Called by value: use return to replace the original value
Called by reference: without using return
list, tuple and dict all fit this type.
Special case:
The whole list was reassigned
return is needed
in this case
◤
Exercise
Name | Age | Room number |
Kevin | 34 | 301 |
James | 67 | 302 |
Ann | 15 | 303 |
Name | Age | Room number |
Jeremy | 40 | 301 |
Kevin | 33 | 304 |
original
new patients
◤
◤
Main function
__ indicate the variable is predefined by python. __name__ will store the name of function which are executed currently. Without importing to other script, __name__ will be __main__ when the script starts to run.
◤
1
2
3
__name__ = “get_sum”
4
__name__ = “__main__”
◤
Exercise
Rewrite the script with a main function
◤
◤
◤
Class
class
constructor
object
method
attribute
◤
◤
Class
◤
Object
◤
Attribute
◤
Constructor
◤
Constructor - self
Already know from the object
self does not need to be
assigned
◤
Method
required
◤
Exercise
How to debug – use print wisely
Script can be downloaded from https://drive.google.com/file/d/1coz2CM_fPYnaORWLdtlrwRFe6X3-nIJR/view?usp=sharing
◤