python自訂函數入門執行個體學習教程

來源:互聯網
上載者:User

這是一篇關於python入門學習教程的自訂函數執行個體

定義一個什麼都不做的函數
 

>>> def a():
... pass
...
>>> def printHello():
... print("hello")
...
>>> printHello()
hello
>>> callable(printHello)
True

顧名思義,callable函數用於判斷函數是否可以調用;
有書上說,callable在Python3.0中已經不再使用,而使用hasattr(func, '__call__')代替;
 

>>> hasattr(printHello, '__call__')
True
 
>>> printHello.__doc__
>>> def printHello():
... 'just print hello'
... print('hello')
...
>>> printHello.__doc__
'just print hello'
 

 
每個函數都有一個__doc__屬性,雙底線表示它是個特殊屬性;
 
內建的help函數非常有用,可以提供有關方法/函數的協助資訊;
 

>>> help(printHello)


函數的注釋資訊包含其中;
雖然printHello函數沒有使用return,可以用一個變數接收傳回值:
 

>>> result = printHello()
hello
>>> result
>>> print(result)
None
 

 
None是Python的內建值,類似Javascript的undefined嗎?
 
定義一個可以接收參數的printStr,用以列印字串
 

>>> def printStr(str):
... print(str)

 
>>> printStr("hello")
hello
 

 
像C++一樣,Python支援預設參數
 

>>> def printStr(str="nothing"):
... print(str)
..
 
>>> printStr()
nothing

傳參方式:
 

>>> a = [1,2]
>>> def try_change_list(a):
... a[:] = [1,1,1]
...
>>> try_change_list(a)
>>> a
[1, 1, 1]

Python的傳參可以理解為按值傳遞(同java,Javascript)?
 
備忘:如果不想讓try_change_list改變原來的對象,可以傳入a[:]
 

>>> a = [1,2]
>>> try_change_list(a[:])
>>> a
[1, 2]

當然,這裡做的是淺拷貝,可以使用copy模組的deepcopy來進行深拷貝;
 
除了支援參數預設值,還支援命名傳參:
 

>>> def sum(a=0, b=0):
... return a + b;
...
>>> sum(2,2)
4
>>> sum(b = 3, a = 4)
7

這種特性在參數較多時比較好用;
 
Python對可變參數列表的支援:
 

>>> def sum(*args):
... s = 0;
... for i in args:
... s += i;
... return s
...
>>> sum(1,2,3,4)
10

一個簡單的求和例子,不同於C/C++的靜態類型,Python並不會限制傳入sum函數的參數的類型:
 

>>> def printArs(*args):
... for a in args:
... print(a)
...
>>> printArs(2, 3, [2,2], (2,), 'df')
2
3
[2, 2]
(2,)
df
>>> printArs(*(2, 3, [2,2], (2,), 'df'))
2
3
[2, 2]
(2,)
df
>>> printArs(*[2, 3, [2,2], (2,), 'df'])
2
3
[2, 2]
(2,)
df

這裡的args對應於Javascript的arguments;
 
除了使用使用元組(tuple)接收可變參數,還可以使用dictionary接收具名引數:
 

>>> def printArs(**args):
... for k in args:
... print(repr(k) + " = " + repr(args[k]))
...
>>>
>>> printArs(name='wyj', age=24)
'name' = 'wyj'
'age' = 24
>>> printArs(**{'name':'wyj', 'age':24})
'name' = 'wyj'
'age' = 24

當然,更複雜地,可以混合使用*arg, **arg, 預設值特性:



Python自訂函數傳參函數設計

 Python裡自訂子函數時,可以在調用時攜帶一些參數到子函數裡去處理。具體用法結構如下:

    def func(arguments):  
         statement  
         statement  
         etc.  

    定義子函數一定要注意(a)在)後加上分號:(第一行最後哦),(b)def下邊的語句塊每行都要用TAB縮排一下!在設計好帶參數的子函數之後就可以在Python程式裡調用了。先舉個例子熱熱身吧!

    #define function: print_msg  
    def print_msg(str):  
        print(str)  
    #define main  
    def main():  
        print("call sub function print_msg")  
        print_msg("jeapedu")  
      
    #programme  
    main()  

  程式執行流程從第10行開始執行即main()這條語句執行,main是自己定義的函數,所以程式進入main這個子函數執行(第6行),執行到第7行時,指令又跳到第3行,當第3行執行完列印語句後回到main第6行下邊,main也執行完了,返回到第10行下邊,程式結束。 程式輸出結果為:

    jeapedu


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.