Python

Python生成器、assertions、匿名函数、继承

2019-02-14  本文已影响20人  松鼠的读书笔记

1、Generators 生成器


(1) yield 和 return 的区别

(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


计算直角三角形的斜边

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


# 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 继承


# 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

狗富贵,互相旺!

上一篇下一篇

猜你喜欢

热点阅读