Guard clauses 保護條款
# guard clauses
def function():
if A:
do A ...
if B:
do B ...
if C:
do C ...
...
以上code每一層都有guard clauses:如果…是對的,再做…。可以用exception handling把code更簡化、增加可讀性且更pythonic。
# use **exception handling**
def function():
if A is not right:
raise Exception1
do A ...
if B is not right:
raise Exception2
do B ...
...
Example
# guard clauses
def devide(a, b):
if type(a) == int and type(b) == int:
if b != 0:
return a / b
else:
return "The 2nd argument cannot be zero."
else:
return "Invalid argument type!"
print(devide(10, "h")) # Invalid argument type!
print(devide(10, 0)) # The 2nd argument cannot be zero.
print(devide(10, 2)) # 5.0
# use exception handling
def devide(a, b):
if type(a) != int or type(b) != int:
raise ValueError("Not valid type given!!!")
if b == 0:
raise ZeroDivisionError("The 2nd argument cannot be zero.")
return a / b
try:
print(devide(10, "h"))
except Exception as e:
print(e)
# Not valid type given!!!
try:
print(devide(10, 0))
except Exception as e:
print(e)
# The 2nd argument cannot be zero.
try:
print(devide(10, 2))
except Exception as e:
print(e)
# 5.0
Context Manager 資源管理器 = with
statement
# traditionally (In Java...)
try:
file = open(“hello.txt”)
data = file.read()
file.close()
except FileNotFoundError:
print(“file not found…”)
# use context manager
try:
with open(“hello.txt”) as file:
data = file.read() # 不用close
except FileNotFoundError:
print(“file not found…”)
可以自製自己的context manager,python contextlib中也有很多內建的context manager可以使用。
Pylint是一個可以分析python程式碼的工具,可以協助找到errors, coding standard等問題。
Example 1
# code in **try.py**
a = 1
b = 2
print(a)
print(B)
# pylint's output
************* Module try
try.py:1:0: C0114: Missing module docstring (missing-module-docstring)
try.py:1:0: C0103: Constant name "a" doesn't conform to UPPER_CASE naming style (invalid-name)
try.py:2:0: C0103: Constant name "b" doesn't conform to UPPER_CASE naming style (invalid-name)
try.py:4:6: E0602: **Undefined variable 'B'** **(undefined-variable)**
------------------------------------------------------------------
Your code has been rated at 0.00/10 (previous run: 0.00/10, +0.00)
# code in **try.py**
'''Testing...'''
A = 1
B = 2
print(A)
print(B)
# pylint's output
--------------------------------------------------------------------
Your code has been rated at 10.00/10 (previous run: 0.00/10, +10.00)
Example 2
# code in **try.py**
def hello():
for volume in [1, 2, 3]:
print(volume)
for volme in [1, 2, 3]:
print(volume)
# pylint's output
************* Module try
try.py:1:0: C0114: Missing module docstring (missing-module-docstring)
try.py:2:0: C0116: Missing function or method docstring (missing-function-docstring)
**try.py:5:8: W0612: Unused variable 'volme' (unused-variable)**
-------------------------------------------------------------------
Your code has been rated at 4.00/10 (previous run: 10.00/10, -6.00)
We can use Python’s standard library unittest .
Example
# in **cap.py**
def cap_test(text):
return text.capitalize()
# in **main_program.py**
import unittest
import cap
class MyTest(unittest.TestCase):
def test_one(self):
text = "sample"
result = cap.cap_test(text)
self.assertEqual(result, "Sample")
def test_two(self):
text = "just testing..."
result = cap.cap_test(text)
self.assertEqual(result, "Just Testing...")
if __name__ == "__main__":
unittest.main()
# output
.F
======================================================================
FAIL: test_two (__main__.MyTest.test_two)
----------------------------------------------------------------------
Traceback (most recent call last):
File "c:\\Users\\USER\\Desktop\\��L\\udemy\\Python+PPTs\\python codes\\main_program.py", line 14, in test_two
self.assertEqual(result, "Just Testing...")
AssertionError: 'Just testing...' != 'Just Testing...'
- Just testing...
? ^
+ Just Testing...
? ^
----------------------------------------------------------------------
Ran 2 tests in 0.003s
FAILED (failures=1)
# **修改** in **cap.py**
def cap_test(text):
return text.title()
# in **main_program.py**
import unittest
import cap
class MyTest(unittest.TestCase):
def test_one(self):
text = "sample"
result = cap.cap_test(text)
self.assertEqual(result, "Sample")
def test_two(self):
text = "just testing..."
result = cap.cap_test(text)
self.assertEqual(result, "Just Testing...")
if __name__ == "__main__":
unittest.main()
# output
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
Python’s functions are first class objects, they are treated like other objects and variables.
Python’s functions can be :
可以被指派給一個變數
def hello():
print("Hello World")
greet = hello
greet() # Hello World
A function可以作為argument被放入B function中
def hello():
print("Hello World")
def call_another_function(other_func):
other_func()
call_another_function(hello) # Hello World
map(function, iterable, ...)
def square(num):
return num ** 2
myList = [1, 2, 3, 4]
result = map(square, myList)
for i in result:
print(i)
# 1
# 4
# 9
# 16
returned by another function
def hello():
def greet():
print("Greet!")
return greet
welcome = hello()
welcome() # Greet!
def hello(name):
def greet(another_name):
print("Hello," + another_name)
def bye(another_name):
print("Bye," + another_name)
if name == "greet":
return greet
else:
return bye
welcome = hello("greet")
goodbye = hello("bye")
welcome("Wilson") # Hello,Wilson
goodbye("Grace") # Bye,Grace
put into a list, tuple or dict
def hello():
print("hello1")
def hello2():
print("hello2")
for func in [hello, hello2]:
func()
# hello1
# hello2
higher-order function 為一個有包含其他函數的函數
@property
is a decorator.