Created
December 13, 2012 10:06
-
-
Save reorx/4275442 to your computer and use it in GitHub Desktop.
tricky and noteworthy arguments passing ways in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 1. multable keyword-argument won't be initialized each time function is called, | |
# it is created and stored at the time the function is defined. | |
# example: list | |
def pri(a=[]): | |
a.append(1) | |
print a | |
pri() | |
pri() | |
# example: dict | |
def pri(b, a={}): | |
a[b] = 1 | |
print a | |
pri('x') | |
pri('y') | |
# example: dict created by function | |
def new_dict(): | |
print 'create dict' | |
return dict() | |
def pri(b, a=new_dict()): | |
a[b] = 1 | |
print a | |
pri('x') | |
pri('y') | |
# 2. dict type function is just a shallow copy | |
d = { | |
'a': [], | |
'b': 1 | |
} | |
c = dict(d) | |
c['b'] = 2 | |
print d, c | |
c['a'].append(1) | |
print d, c | |
# 3. change on keyword-argument may cause change on passing dict | |
def pri(**kwgs): | |
kwgs['a'].append(1) | |
d = {'a': []} | |
pri(**d) | |
print d |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment