Python中常见的参数错误如何避免?
- 内容介绍
- 文章标签
- 相关推荐
本文共计272个文字,预计阅读时间需要2分钟。
pythondef add(a, b): a +=b return a
class Company: def __init__(self, name, staffs=[]): self.name=name self.staffs=staffs
def add_staff(self, staff_name): self.staffs.append(staff_name)
def remove_staff(self, staff_name): self.staffs.remove(staff_name)
def add(a, b):a += b
return a
class Company:
def __init__(self, name, staffs=[]):
self.name = name
self.staffs = staffs
def add(self, staff_name):
self.staffs.append(staff_name)
def remove(self, staff_name):
self.staffs.remove(staff_name)
if __name__ == "__main__":
com1 = Company("com1", ["bobby1", "bobby2"])
com1.add("bobby3")
com1.remove("bobby1")
print (com1.staffs)
com2 = Company("com2")
com2.add("bobby")
print(com2.staffs)
print (Company.__init__.__defaults__)
com3 = Company("com3")
com3.add("bobby5")
print (com2.staffs)
print (com3.staffs)
print (com2.staffs is com3.staffs)
# a = 1
# b = 2
#
# a = [1,2]
# b = [3,4]
#
# a = (1, 2)
# b = (3, 4)
#
# c = add(a, b)
#
# print(c)
# print(a, b)
['bobby2', 'bobby3']
['bobby']
(['bobby'],)
['bobby', 'bobby5'] #com2.staffs
['bobby', 'bobby5']#com3.staffs
True
、、、、、
com2.staffs和com3.staffs使用的同一个内存空间,,这是python内部处理机制造成的,默认的staffs是一个可变对象,所以当传递对象参数到函数中是注意是否是可变对象
本文共计272个文字,预计阅读时间需要2分钟。
pythondef add(a, b): a +=b return a
class Company: def __init__(self, name, staffs=[]): self.name=name self.staffs=staffs
def add_staff(self, staff_name): self.staffs.append(staff_name)
def remove_staff(self, staff_name): self.staffs.remove(staff_name)
def add(a, b):a += b
return a
class Company:
def __init__(self, name, staffs=[]):
self.name = name
self.staffs = staffs
def add(self, staff_name):
self.staffs.append(staff_name)
def remove(self, staff_name):
self.staffs.remove(staff_name)
if __name__ == "__main__":
com1 = Company("com1", ["bobby1", "bobby2"])
com1.add("bobby3")
com1.remove("bobby1")
print (com1.staffs)
com2 = Company("com2")
com2.add("bobby")
print(com2.staffs)
print (Company.__init__.__defaults__)
com3 = Company("com3")
com3.add("bobby5")
print (com2.staffs)
print (com3.staffs)
print (com2.staffs is com3.staffs)
# a = 1
# b = 2
#
# a = [1,2]
# b = [3,4]
#
# a = (1, 2)
# b = (3, 4)
#
# c = add(a, b)
#
# print(c)
# print(a, b)
['bobby2', 'bobby3']
['bobby']
(['bobby'],)
['bobby', 'bobby5'] #com2.staffs
['bobby', 'bobby5']#com3.staffs
True
、、、、、
com2.staffs和com3.staffs使用的同一个内存空间,,这是python内部处理机制造成的,默认的staffs是一个可变对象,所以当传递对象参数到函数中是注意是否是可变对象

