Chinaunix首页 | 论坛 | 博客
  • 博客访问: 66644
  • 博文数量: 36
  • 博客积分: 2510
  • 博客等级: 少校
  • 技术积分: 410
  • 用 户 组: 普通用户
  • 注册时间: 2009-04-04 12:39
文章分类

全部博文(36)

文章存档

2010年(1)

2009年(35)

我的朋友
最近访客

分类: LINUX

2009-04-24 23:48:09

PYTHON 之结构体,全局变量,函数参数,lambda编程 ,generator(yield)使用以及如何自己构建switch结构

***********************
pass
pass可以模拟struct结构

class Data
    pass

d = Data()
d.a = 2
d.b = 4

print d.a
print d.b

***********************
子函数传参数的有趣的地方
def cheeseshop(kind, *arguments, **keywords):
    print "-- Do you have any", kind, "?"
    print "-- I'm sorry, we're all out of", kind
    for arg in arguments: print arg #一个星号的arguments表示传入n元组tuple,可以想像成list或者数组
    print "-" * 40
    keys = keywords.keys()#两个星号的表示传入的是一个字典结构
    keys.sort()
    for kw in keys: print kw, ":", keywords[kw]

cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", shopkeeper='Michael Palin', client="John Cleese", sketch="Cheese Shop Sketch")

除了第一个参数被当做kind的值,剩下的将被构成一个tuple(和list相似,理解成数组吧),这些被当成整体传入函数cheeseshop,剩下的形如k=v的则全部被构建成一个词典dictionary 对象,然后传进入。
感觉这样的主要好处是定义函数cheeseshop的时候需要写的参数少了,同样类型的使用argument就好了,但是如果给别人调用的话,这样写恐怕非常不好。
当然,如果你写成
def testArg(*argument,*argument):
    for a in argument: print a
那是不对的, 最多只能有一个参数是*的形式

***********************
使用全局变量
比如在外面定义了a,则函数内部如果想使用全局变量a,加上
global a

***********************
yield的用法
yield 是generator的关键词,看看generator
http://www.python.org/dev/peps/pep-0255/ 说明了采用generator的原因,并给出了一些restriction,最后使用binary tree作为例子
http://www.ibm.com/developerworks/library/l-pycon.html?S_TACT=105AGX52&S_CMP=cn-a-x
A generator is a function that remembers the point in the function body where it last returned. Calling a generator function a second (or nth) time jumps into the middle of the function, with all local variables intact from the last invocation.
yield 产生一个generator,这个generator有两个好处:
1)记录了产生generator的函数的内部状态,也就是数据的值
2)记录了该函数正在执行的语句,下一次调用将从上次执行yield语句的下一条开始执行。

***********************
switch
python没switch,但是有多种方法来实现switch,看看下面的例子把
#!/usr/local/bin/python
# coding: UTF-8

#first case

a = 2

def print1():
    print 1

def print2():
    print 2

def print3():
    print 3

def print1():
    print 'default'
#使用单条语句,然后使用exec函数执行

valuesStatement = {
        1: 'print 1',
        2: 'print 2',
        3: 'print 3'
        }

#使用函数,即获得了函数句柄,然后就可以直接调用
valuesFunc = {
        1: print1,
        2: print2,
        3: print3
        }

exec(valuesStatement.get(1,'print 2'))
valuesFunc.get(1,'default')()#注意,这里括号的位置,其实就是相当于首先取得函数指针,然后调用,如果你直接
print valuesFunc.get(1,'default') #的话,你就会看到函数的地址

#second case
#使用lambda, definition
#http://en.wikipedia.org/wiki/Lambda_calculus
#~selinger/papers/lambdanotes.pdf,看看这篇文章可以更好的理解lambda,我看了Church理论证明之前的部分,理解了lambda怎么回事,但是lambda和函数编程之间的关系确解释不清楚,感觉函数编程并不依赖与lambda

#lumbda 如何使用
def make_incrementor(n):
    return lambda x: x + n
f = make_incrementor(4) #这里相当于我们获得了一个函数
print f(3) #call

#那么使用lumbda实现switch吧,类似前面所属使用statement的方式,只是不需要使用exec了
result = {
  'a': lambda x: x * 5,
  'b': lambda x: x + 7,
  'c': lambda x: x - 2
  }

f = result['a']
print f(3)

#third case
#使用类

 #This class provides the functionality we want. You only need to look at
 # this if you want to know how this works. It only needs to be defined
 # once, no need to muck around with its internals.
class switch(object):
   
    def __init__(self, value):
        self.value = value
        self.fall = False

    def __iter__(self ):
        """Return the match method once, then stop"""
        yield self.match
        raise StopIteration
    def match(self, *args):
        """Indicate whether or not to enter a case suite"""
        if self.fall or not args:#为Ture或者默认,默认是没有参数的
            return True
        elif self.value in args: # changed for v1.5, see below
            self.fall = True
            return True
        else:
            return False

# The following example is pretty much the exact use-case of a dictionary,
# but is included for its simplicity. Note that you can include statements
# in each suite.
v='ten'

for case in switch(v):#因为重写了 def __iter__(self):,而该函数返回match函数,从而可以传入参数并判断是否相等
    if case('one'):#这里和普通case不同,前面多了个if,作者只是在形式上模拟了switch-case,实际用的是if
        print 1
        break
    if case('two'):
        print 2
        break
    if case('ten'):
        print 10
        break
    if case('eleven'):
        print 11
        break
    if case(): # default, could also just omit condition or 'if True'
        print "something else!"
# No need to break here, it'll stop anyway

 #无需多解释了,作者巧妙的利用了python的for功能来让iter返回函数指针,进而接受参数确定是否执行之。
 #要注意,case前面必须有if,否则,就不奏效拉,因为作者就是用了mathc的返回值

阅读(829) | 评论(0) | 转发(0) |
0

上一篇:lambda和函数编程

下一篇:SHELL 编程

给主人留下些什么吧!~~