Top 10 Mistakes that Python Programmers Make

文章:python的十大易错点。

来源:

http://www.toptal.com/python/top-10-mistakes-that-python-programmers-make



1、  Common Mistake #1: Misusing expressions as defaults for functionarguments

代码驱动问题:函数参数缺省值的误用。

>>>def fn(bar=[]):

bar.append("allen")

return bar

 

>>>fn()

['allen']

>>>fn()

['allen','allen']

>>> 

缺省值表达式bar=[]只有在首次运行define函数时才会运行一次。之后会继承上次的bar

>>>def fn(bar=None):

bar=bar or []  #if not bar then evaluate to []

bar.append("allen")

return bar

 

>>>fn()

['allen']

>>>fn()

['allen']

>>> 

None代表一个空的对象。

求解:难道这里的赋值表达式就会每次都运行吗?

2、  Common Mistake #2: Using class variables incorrectly

代码驱动问题:类变量的继承问题

>>>class A(object):

x=1

>>>class B(A):

pass

 

>>>print A.x,B.x

1 1

>>>A.x=10

>>>print B.x

10

>>>B.x=11

>>>print A.x ,B.x

10 11

>>> 

B自己没有定义B.x之前,B.x=A.x,一旦B定义了B.x,B.x和A.x就一毛钱关系也没有

 

3、  Common Mistake #3: Specifying parameters incorrectly for anexception block

代码驱动问题:如何同时检测多个错误

try:

    ####

   except ValueError, IndexError:  # To catch both exceptions, this is wrong

pass

解决:

try:

    ####

 except (ValueError, IndexError) as e: 

pass

 

4、  Common Mistake #4: Misunderstanding Python scope rules

代码驱动问题:正确理解变量的作用域

x=4

>>>def foo():

                    x+=6

上面程序的错误:还没声明就像引用

UnboundLocalError: local variable 'x' referenced beforeassignment

但是如果用append代替+=,错误就会消失。

x=[1,2,3]

>>>def foo():

              x.append(4)

           >>>x

                    12 3 4

解决:

           传递参数:deffoo(x),或者使用全局变量

           def foo():

                             globalx

                             x+=6

 

5、  Common Mistake #5: Modifying a list while iterating over it

代码驱动问题:不要在遍历list的时候增删数据

正确的做法:在0-9之间找出偶数:遍历0-9,找出偶数存入另一个结构中。

>>>odd = lambda x : bool(x % 2)

>>>numbers = [n for n in range(10)]

>>>numbers[:] = [n for n in numbers if not odd(n)] # ahh, the beauty of it all

>>>numbers

[0, 2, 4, 6, 8]

错误的用法:遍历0-9,踢掉奇数。

for i inrange(len(numbers)):

     if odd(numbers[i]):

         del numbers[i] 

 

6、  Common Mistake #6: Confusing how Python binds variables in closures

代码驱动问题:变量的后期绑定。

下面的代码中,i:0-4,因为是late binding,所以变量i的值是一层一层向上兼容,即取最终的4.

def a():

return [lambda x:i*x for i in range(5)]

>>>for b in a():

print b(2)

 

8

8

8

8

8

解决:变量i还来不及向上绑定就被设置缺省值了,有点diao。

>>> def create_multipliers():

    return [lambda x, i=i : i * x for i in range(5)]

>>> for multiplier increate_multipliers():

   print multiplier(2)

0

2

4

6

8

 

 

7、  Common Mistake #7: Creating circular module dependencies(不解,求教)

问题驱动:创建回环依赖。

In a.py:

import b

def f():

   return b.x

print f()

 

b.py:

import a

x = 1

def g():

print a.f()

运行a.py失败,但如果删掉其中的print f()则可以运行

运行b.py成功,输出1

 

 

8、  Common Mistake #8: Name clashing with Python Standard Librarymodules

问题:自己做的模块名不要和python内部的同名,以免importError

9、  Common Mistake #9: Failing to address differences between Python 2and Python 3(略不懂)

问题:python2和python3之间的寻址和版本迁移问题

 

10、             Common Mistake #10: Misusingthe __del__ method

问题:乱用__del__

import foo

classBar(object):

    def __del__(self):

        foo.cleanup(self.myhandle)

 

>>> import mod

mybar = mod.Bar() 出错

因为:when the interpreter shuts down, the module’s global variables areall set to None. As a result, in the above example, at the point that __del__is invoked, the name foo has already been set to None.

 



写在最后的话:

后面几点不是很懂,前面几点感觉不是很有用,就这样也能占我三个小时,我竟无言以对

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值