Python的類成員變量默認初始值的坑
阿新 • • 發佈:2019-02-02
python程序 def ive pri com 內存 指向 code 函數 問題發現:一個循環內,缺省值初始化同名變量,其中的list成員不是空,會延續之前同名變量的值。
示例代碼:
# Define class class Variant(): # use def __init__(self, price = 500, description = ‘default description‘, values = [‘‘, ‘‘, ‘‘]): self.price = price self.description = description self.values = values def __str__(self): return ‘price: {}, description: {}, values: {}‘.format(self.price, self.description, self.values) variant_list = [] # Create instance with same name iteratively for i in range(3): current_variant = Variant() if i == 1: current_variant.values[2] = ‘hello‘ current_variant.price = i current_variant.description = ‘description of variant: {}‘.format(i) variant_list.append(current_variant) # Test results for variant in variant_list: print(str(variant))
結果:所有實例的values列表值相同
原因:“可選參數默認值的設置在Python中只會被執行一次,也就是定義該函數的時候”如此使用缺省值初始化,list成員指向的是同一個list(地址),如果只是修改其中一個元素(而不是賦值新的list開辟新內存),那麽所有instance的list成員都會被修改。
解決方法:直接在構造方法中置為空(self.values = [‘‘, ‘‘, ‘‘]
),之後各個修改值
reference:Python 類成員變量使用缺省值初始化時要註意的一個坑
Python程序員最常犯的十個錯誤
Python的類成員變量默認初始值的坑