Ä
人言è½æ—¥æ˜¯å¤©æ¶¯ï¼Œæœ›æžå¤©æ¶¯ä¸è§å®¶
Please look at below code snippet:
class test():
def __init__(self, a, dic={}):
self.a = a
self.dic = dic
print('__init__ params:',a, dic)
def get(self):
self.dic[1] = 2
self.dic[4] = 5
def foo():
print('in foo function')
bar = test(1)
bar.get()
if __name__ == '__main__':
foo()
foo()
-----------------------
Result:
in foo function
__init__ params: 1 {}
in foo function
__init__ params: 1 {1: 2, 4: 5}
But my expect result is :
in foo function
__init__ params: 1 {}
in foo function
__init__ params: 1 {}
it seems that the default value for dic doesn't work on the second
call for the class test.
It's wired. Who can give a explaination for this scenario?
class test():
def __init__(self, a, dic={}):
self.a = a
self.dic = dic
print('__init__ params:',a, dic)
def get(self):
self.dic[1] = 2
self.dic[4] = 5
def foo():
print('in foo function')
bar = test(1)
bar.get()
if __name__ == '__main__':
foo()
foo()
-----------------------
Result:
in foo function
__init__ params: 1 {}
in foo function
__init__ params: 1 {1: 2, 4: 5}
But my expect result is :
in foo function
__init__ params: 1 {}
in foo function
__init__ params: 1 {}
it seems that the default value for dic doesn't work on the second
call for the class test.
It's wired. Who can give a explaination for this scenario?