默认参数:函数的参数可以有一个默认值, 如果提供有默认值,在函数定义中, 参数以赋值语句的形式提供。事实上这仅仅是提供默认参数的语法,它表示函数调用时如果没有提供这个参数, 它就取这个值做为默认值
def foo(debug=True):
'determine if in debug mode with default argument'
if debug:
print'in debug mode'
print 'done'
foo()
创建类实例
1 classFooClass(object):2 """my very first class: FooClass"""
3 version = 0.1
4
5 def __init__(self, nm='John Doe'):6 """constructor"""
7 self.name =nm8 print 'Created a class instance for', nm9
10 defshowname(self):11 """display instance attribute and class name"""
12 print 'Your name is', self.name13 print 'My name is', self.__class__.__name__
14
15 defshowver(self):16 """display class(static) attribute"""
17 printself.version18
19 defaddMe2Me(self, x):20 """apply + operation to argument"""
21 return x +x22
23 foo1 = FooClass() #Created a class instance for John Doe
24 foo1.showname() #Your name is John Doe #My name is FooClass
25
26 foo1.showver() #0.1
27
28 print foo1.addMe2Me(5) #10
29
30 print foo1.addMe2Me('xyz') #xyzxyz
注:每个方法的调用都返回我们期望的结果。比较有趣的数据是类名字。在showname()方法中,我们显示 self.__class__.__name__ 变量的值。对一个实例来说, 这个变量表示实例化它的类的名字。(self.__class__引用实际的类)。在我们的例子里, 创建类实例时我们并未传递名字参数, 因此默认参数 'John Doe' 就被自动使用。
type() 和 isinstance()
#!/usr/bin/env python
def displayNumType(num):
print num, 'is',
if isinstance(num, (int, long, float, complex)):
print 'a number of type:', type(num).__name__
else:
print 'not a number at all!'
displayNumType(-69)
displayNumType(9999999999999999999999L)
displayNumType(98.6)
displayNumType(-5.2+1.9j)
displayNumType('xxx')
答案:
-69 is a number of type: int
9999999999999999999999 is a number of type: long
98.6 is a number of type: float
(-5.2+1.9j) is a number of type: complex
xxx is not a number at all!
#多元赋值 x,y,z = 1,2,3 #等于 (x, y, z) = (1, 2, 3)
1 #range()函数经常和len()函数一起用于字符串索引
2 foo = 'abc'
3 for i inrange(len(foo)):4 print foo[i], '(%d)' %i5
6 #enumerate
7 foo = 'abc'
8 for i in enumerate(foo,1):9 printi10
11 #列表解析
12 l = [x **2 for x in range(4)]13 for w inl:14 printw15
16 #函数 功能
17 #abs(num) 返回 num 的绝对值
18 #coerce(num1, num2) 将num1和num2转换为同一类型,然后以一个 元组的形式返回。
19 #divmod(num1, num2) 除法-取余运算的结合。返回一个元组(num1/num2,num1 %num2)。对浮点数和复数的商进行下舍入(复数仅取实数部分的商)
20 #pow(num1, num2, mod=1) 取 num1 的 num2次方,如果提供 mod参数,则计算结果再对mod进行取余运算
21 #round(flt, ndig=0) 接受一个浮点数 flt 并对其四舍五入,保存 ndig位小数。若不提供ndig 参数,则默认小数点后0位。
22 #round() 仅用于浮点数。(译者注:整数也可以, 不过并没有什么
23
24 #ASCII转换函数
25 ord('a') 97
26 chr(91) 'a' #将ASCII值的数字转换成ASCII字符,范围只能是0 <= num <= 255。
27
28 list(iter) 把可迭代对象转换为列表29 str(obj) 把obj 对象转换成字符串(对象的字符串表示法)30 unicode(obj) 把对象转换成Unicode 字符串(使用默认编码)31 basestring() 抽象工厂函数,其作用仅仅是为str 和unicode 函数提供父类,所以不能被实例化,也不能被调用32 tuple(iter) 把一个可迭代对象转换成一个元组对象