为了让初学 Python 的程序员避免犯同样的错误,以下列出了我学习 Python 时犯的三种错误。这些错误要么是我长期以来经常犯的,要么是造成了需要几个小时解决的麻烦。 -- Pete Savage
本文导航
-1、 可变数据类型作为函数定义中的默认参数 …… 07%
-2、 可变数据类型作为类变量 …… 35%
-3、 可变的分配错误 …… 53%
编译自: https://opensource.com/article/17/6/3-things-i-did-wrong-learning-python
作者: Pete Savage
译者: polebug
这些错误会造成很麻烦的问题,需要数小时才能解决。
def search_for_links(page, add_to=[]):
new_links = page.search_for_links()
add_to.extend(new_links)
return add_to
def fn(var1, var2=[]):
var2.append(var1)
print var2
fn(3)
fn(4)
fn(5)
[3]
[4]
[5]
[3]
[3, 4]
[3, 4, 5]
fn(3, [4])
[4, 3]
def fn(var1, var2=None):
if not var2:
var2 = []
var2.append(var1)
def search_for_links(page, add_to=None):
if not add_to:
add_to = []
new_links = page.search_for_links()
add_to.extend(new_links)
return add_to
def func(message="my message"):
print message
class URLCatcher(object):
urls = []
def add_url(self, url):
self.urls.append(url)
a = URLCatcher()
a.add_url('http://www.google.com')
b = URLCatcher()
b.add_url('http://www.bbc.co.hk')
['http://www.google.com', 'http://www.bbc.co.uk']
['http://www.google.com', 'http://www.bbc.co.uk']
class URLCatcher(object):
def __init__(self):
self.urls = []
def add_url(self, url):
self.urls.append(url)
a = {'1': "one", '2': 'two'}
b = a
b['3'] = 'three'
{'1': "one", '2': 'two', '3': 'three'}
{'1': "one", '2': 'two', '3': 'three'}
c = (2, 3)
d = c
d = (4, 5)
b = a[:]
b = a.copy()
欢迎光临 51学通信论坛2017新版 (http://bbs.51xuetongxin.com/) | Powered by Discuz! X3 |