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__