python函数结构_PYTHON 之结构体,全局变量,函数参数,lambda编程 等
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
#http://www.mathstat.dal.ca/~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的返回值
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的python函数结构_PYTHON 之结构体,全局变量,函数参数,lambda编程 等的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎么看股票涨停幅度?
- 下一篇: 除权除息日买进股票是亏大了吗?