Consider the following codes
class User: def __init__(self, name, hobby=[]): self.name = name self.hobby = hobby def add_hobby(self, hobby): self.hobby.append(hobby) def remove_hobby(self, hobby): self.hobby.remove(hobby) def __str__(self): return self.name + ',' + '-'.join(self.hobby) if __name__ == '__main__': u1 = User(' Bob ' ) u1.add_hobby ( ' football ' ) Print (U1) # Xiaoming, soccer Print (ID (u1.hobby)) # 2074461954696 U2 = the User ( ' small strong ' ) u2.add_hobby ( ' beauty ' ) Print (U2 ) # Xiaoqiang, football - beauty Print (U1) # Xiao Ming, football - beauty Print (the above mentioned id (u2.hobby)) # 2074461954696
analysis:
We created two User objects are u1, u2, but my hobby when modifying the properties of u2, u1 has caused a change in the properties of the object hobby
The fundamental reason is because the creation u1, u2 when the object does not pass this hobby list object, the default on the air, and this air is globally unique, point to the same memory address, so modifications can also cause changes in u2 u1, and
Therefore, when we pass the reference list, should special attention. This is a pit.