python

 r 使用 原始字符串

任意参数的列表

>>> def concat(*args, sep="/"):
...     return sep.join(args)
...>>> concat("earth", "mars", "venus")'
earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")'
earth.mars.venus'

分拆参数

>>> list(range(3, 6))            # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args))            # call with arguments unpacked from a list
[3, 4, 5]
>>> def parrot(voltage, state='a stiff', action='voom'):
...     print("-- This parrot wouldn't", action, end=' ')
...     print("if you put", voltage, "volts through it.", end=' ')
...     print("E's", state, "!")
...>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

Python 参数知识(变量前加星号的意义)

在运行时知道一个函数有什么参数,通常是不可能的。另一个情况是一个函数能操作很多对象。更有甚者,调用自身的函数变成一种api提供给可用的应用。



注意args和kwargs只是python的约定。任何函数参数,你可以自己喜欢的方式命名,但是最好和python标准的惯用法一致,以便你的代码,其他的程序员也能轻松读懂。




在参数名之前使用一个星号,就是让函数接受任意多的位置参数。

>>> def multiply(*args):
…     total = 1
…     for arg in args:
…         total *= arg
…     return total

>>> multiply(2, 3)
6
>>> multiply(2, 3, 4, 5, 6)
720

python把参数收集到一个元组中,作为变量args。显式声明的参数之外如果没有位置参数,这个参数就作为一个空元组。

<span  rgb(0, 0, 0); font-family: Arial; line-height: 26px; font-size: small;">关键字参数

python在参数名之前使用2个星号来支持任意多的关键字参数。

>>> def accept(**kwargs):
…     for keyword, value in kwargs.items():
…         print "%s => %r" % (keyword, value)

>>> accept(foo='bar', spam='eggs')
foo => 'bar'
spam => 'eggs'

注意:kwargs是一个正常的python字典类型,包含参数名和值。如果没有更多的关键字参数,kwargs就是一个空字典。

混合参数类型

任意的位置参数和关键字参数可以和其他标准的参数声明一起使用。混合使用时要加些小心,因为python中他们的次序是重要的。参数归为4类,不是所有的类别都需要。他们必须按下面的次序定义,不用的可以跳过。

1)必须的参数
2)可选的参数
3)过量的位置参数
4)过量的关键字参数

def complex_function(a, b=None, *c, **d):

这个次序是必须的,因为*args和**kwargs只接受那些没有放进来的其他任何参数。没有这个次序,当你调用一个带有位置参数的函数,python就不知道哪个值是已声明参数想要的,也不知道哪个被作为过量参数对待。

也要注意的是,当函数能接受许多必须的参数和可选的参数,那它只要定义一个过量的参数类型即可。

传递参数集合

除了函数能接受任意参数集合,python代码也可以调用带有任意多数量的函数,像前面说过的用星号。这种方式传递的参数由python扩展成为参数列表。以便被调用的函数
不需要为了这样调用而去使用过量参数。python中任何可调用的,都能用这种技法来调用。并且用相同的次序规则和标准参数一起使用。

>>> def add(a, b, c):
…     return a + b + c

>>> add(1, 2, 3)
6
>>> add(a=4, b=5, c=6)
15
>>> args = (2, 3)
>>> add(1, *args)
6
>>> kwargs={'b': 8, 'c': 9}
>>> add(a=7, **kwargs)
24
>>> add(a=7, *args)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add() got multiple values for keyword argument 'a'
>>> add(1, 2, a=7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add() got multiple values for keyword argument 'a'

注意这个例子的最后几行,特别留意当传递一个元组作为过量的位置参数时,是否要显式的传递关键字参数。因为python使用次序规则来扩展过量的参数,那位置参数要放在前面。这个例子中,最后两个调用是相同的,python不能决定那个值是给a的。

python 错误类型

1、NameError:尝试访问一个未申明的变量

NameError: name 'v' is not defined

>>> v = 1/0



3、SyntaxError:语法错误


SyntaxError: invalid syntax (<pyshell#14>, line 1)

>>> List = [2]

Traceback (most recent call last):

    List[3]



5、KeyError:字典关键字不存在

>>> Dic['3']

  File "<pyshell#20>", line 1, in <module>

KeyError: '3'

>>> f = open('abc')



7、AttributeError:访问未知对象属性


 def Work():

>>> w = Worker()

Traceback (most recent call last):

    w.a

Traceback (most recent call last):

    int('d')



9、TypeError:类型错误


>>> iVal = 22

Traceback (most recent call last):

    obj = iStr + iVal;



10、AssertionError:断言错误


Traceback (most recent call last):

    assert 1 != 1

http://blog.csdn.net/fcoolx/article/details/4202872

11、 NotImplementedError:方法没实现引起的异常

    示例:

class Base(object):
    def __init__(self):
        pass

    def action(self):
        raise NotImplementedError

 

13、         如果你不确定数据类型是字典还是列表时,可以用 14、StandardError 标准异常。

 

    除StopIterationGeneratorExitKeyboardInterrupt 和SystemExit外,其他异常都是StandarError的子类。

python 笔记

1. %s, %d, %f用法

在python中,print语句和字符操作符结合使用,可实现字符串替换功能。

%s—表示由一个字符串来替换

%d—表示由一个整型来替换

%f—表示由一个浮点型来替换

eg:

>>> print "%s is number %d!" % ("Python",1)

Python is number 1!

 

2.raw_input()内建函数

raw_input–从标准输入读取一个字符串,并自动删除串尾的换行字符。

a)可将读取的数据赋值给一个变量,作再次使用

>>> user=raw_input("enter your name:")

enter your name:jane

>>> print "your login is:", user

your login is: jane

 

b)也可使用int()函数将输入的字符串转换为整型

>>> num=raw_input("Now enter a number:")

Now enter a number:1023

>>> print "doubling your number: %d" %(int(num)*2)

doubling your number: 2046

>>> print "doubling your number: %d" %(num *2)

Traceback (most recent call last):

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

TypeError: %d format: a number is required, not str