高级用法 Advance
递归 Recursion
# 3! = 3 * 2 * 1 = 6
def factorial(n):
if n== 1: return 1
reutrn n * factorial(n-1)
factorial(3) # 6
装饰器 Decorators
def logtime(func):
def wrapper():
# do something before
print("before")
val = func()
print("after")
# do something after
return val
return wrapper
@logtime
def hello():
print("hello")
hello()
# before
# hello
# after
Docstrings
def increment(n):
"""Increment a number"""
return n + 1
dog.py
"""Dog module
This module does ... blablabla and provides the following classes:
- Dog
...
"""
class Dog(Animal):
"""A class representing a dog"""
def __init__(self, name, age):
"""Initialize a new dog"""
self.name = name
self.age = age
def bark(self):
"""Let the dog bark"""
print("woof!")
print(help(Dog))
Annotations
def increment(n: int) -> int:
return n + 1
count: int = 0
Eceptions
try:
# some lines of code
except <ERROR1>:
# handler <ERROR1>
except <ERROR2>:
# handler <ERROR2>
except:
# handler except
else:
# no exceptions were raised, the code ran successfully
finally:
# do something in any case
try:
result = 2 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
result = 1
print(result)
# Cannot divide by zero!
# 1
try:
raise Exception("An error!")
except Exception as error:
print("inside")
print(error)
# An error!
class DogNotFoundException(Excpetion):
pass
try:
raise DogNotFoundException()
except DogNotFoundException:
print("Dog not found!")
# inside
# Dog not found!
With
filename = "/Users/flavio/test.txt"
try:
file = open(filename, "r")
content = file.read()
print(content)
finally:
file.close()
filename = "/Users/flavio/test.txt"
with open(filename, "r") as file:
content = file.read()
print(content)
List compression
numbers = [1, 2, 3, 4, 5]
numbers_power_2 = [n**2 for n in numbers]
# numbers_power_2 = list(map(lambda n: n**2, numbers))
print(numbers_power_2) # [1, 4, 9, 16, 25]