Python生成器、assertions、匿名函数、继承
2019-02-14 本文已影响20人
松鼠的读书笔记
1、Generators 生成器
- Generators are a kind of iterator that are defined like functions. A generator function looks just like a regular function, except that it uses yield instead of return.
- powerful , can improve the efficiency of your program
(1) yield 和 return 的区别
- yield : return values to the function but not end the iteration
- return : return values to the function and end the iteration
(2)Examples about generator
# a list comprehension
print "max in list:",max([num*2-3 for num in range(7)])
# a generator expression
print "max in gen:",max(num*2-3 for num in range(7))
# a generator function
def genfunc(limit):
num = 0
while num < limit:
yield num
num = num + 1
2、Assertions
- check whether certain statement holds in the program
- very powerful tool to help you catch errorr right as they occur
- very useful for writing and debuging
计算直角三角形的斜边
def hypotenuse(sidea,sideb):
"""
calculate the length of the hypotenuse of a right triangle
with sides 0f length sidea and sideb
"""
# computing hypotenuse
hyp = math.sqrt(sidea**2 + sideb**2)
# make sure value is reasonable
assert hyp > sidea and hyp > sideb, "hypotenuse too short"
assert hyp < (sidea + sideb), "hypotenuse too long"
return hyp
不变量invariants
def iterative_factorial(num):
answer = 1
index = 0
# answer == math.factorial(index) is an invariant
assert answer == math.factorial(index)
while index < num:
index += 1
answer *= index
assert answer == math.factorial(index)
return answer
3、Anonymous functions - lambda
- 匿名函数格式如下: lambda x, y : x * y,其中lambda是关键字,x,y是arguments, x*y是函数返回的值
- 如函数简单,可直接使用关键字lambda创建匿名函数,常用于高阶函数中,使代码更简洁易懂
# anonymous functions - lambda
def square(val):
return val**2
data = [1,3,6,9,18]
data1 = map(square,data)
print data1
data2 = map(lambda x: x**2, data)
print data2
def even(val):
return val%2 == 0
data3 = filter(even,data)
print data3
data4 = filter(lambda val: val%2==0, data)
print data4
4、Inheritance 继承
- inheritance : class and subclass
# simple inheritance
class Base:
def hello(self):
print "hello"
def message(self,msg):
print msg
class Sub(Base):
def message(self,msg):
print "sub:",msg
obj = Sub()
obj.hello()
obj.message("what's going to happen?")
# simple example of using inheritance
class Base:
"""
simple base class
"""
def __init__(self,num):
self._number = num
def __str__(self):
"""
return human readable string.
"""
return str(self._number)
class Sub(Base):
"""
simple sub class
"""
def __init__(self,num):
Base.__init__(self, num)
obj = Sub(42)
print obj
狗富贵,互相旺!