Python基礎教程---讀書筆記六

1. callable()函數用來判斷函數是否能夠調用,返回True/False,Python 3.0後不可用。c++

2. 定義函數:'def function(parameter1, parameter2,...):'。ide

3. 文檔字符串:在函數的開頭寫下字符串;使用__doc__或者help()函數訪問函數

   >>> def myfun(x):spa

   ...     'This is my function to print x.'繼承

   ...     print 'x=', x作用域

   ... 文檔

   >>> myfun.__doc__字符串

   'This is my function to print x.'it

   >>> help(myfun)io

4. 函數中return默認返回的是None.

5. 函數參數存儲在局部做用域,字符串、數字和元組不可改變,可是列表和字典是能夠改變。

6. 函數有位置參數和關鍵字參數,後者能夠用來設置默認值。

7. 當函數的參數數量不定時,使用星號(*)和雙星號(**);'*'針對元組,'**'針對字典;

   >>> def print_params(title, *pospar, **keypar):

   ...     print title

   ...     print pospar

   ...     print keypar

   ...

   >>> print_params('Test:', 1, 3, 4, key1=9, key2='abc')

   Test:

   (1, 3, 4)

   {'key2': 'abc', 'key1': 9}

   >>> print_params('Test:')

   Test:

   ()

   {}

   >>>

   >>> param1 = (3, 2)

   >>> param2 = {'name': 'def', 'age': 20}

   >>> print_params('Test1:', *param1, **param2)

   Test1:

   (3, 2)

   {'age': 20, 'name': 'def'}

8. 若是變量名相同,函數內的局部變量會屏蔽全局變量,除非使用golbal聲明爲全局變量。


9. 類的方法能夠在外部訪問,甚至綁定到一個普通函數上或者被其餘變量引用該方法

   >>> class Bird:

   ...     song = 'Squaawk!'

   ...     def sing(self):

   ...             print self.song

   ...

   >>> bird = Bird()

   >>> bird.sing()

   Squaawk!

   >>> birdsong = bird.sing

   >>> birdsong()

   Squaawk!

   >>>

   >>> def newsing():

   ...     print "I'm new sing"

   ...

   >>> bird.sing = newsing

   >>> bird.sing()

   I'm new sing


10. 若是想要定義私有方法,能夠在方法前加上下劃線

   >>> class Bird:

   ...     def __sing(self):

   ...             print "I'm singing!"

   ...     def ex_sing(self):

   ...             self.__sing()

   ...

   >>> bird = Bird()

   >>> bird.ex_sing()

   I'm singing!

   >>> bird.__sing()

   Traceback (most recent call last):

   File "<stdin>", line 1, in <module>

   AttributeError: Bird instance has no attribute '__sing'


11. 注意類的命名空間使得全部類的實例均可以訪問的變量

   >>> class MemberCounter:

   ...     members = 0

   ...     def init(slef):

   ...             MemberCounter.members += 1

   上面類MemberCounter中的members變量像是一個c++中的static變量


12. 繼承超類的方法:class SPAMFilter(Filter, SaveResult);

   注意當多個超類擁有相同名稱的方法是,前面的(Filter)的方法會覆蓋後面的(SvaeResult);

   用isssubclass(SPAMFilter, Filter)函數判斷一個累是不是另外一個類的子類;

   用類的特殊屬性__bases__查看類的基類,SPAMFilter.__bases__

相關文章
相關標籤/搜索