首页 > 编程语言 > 详细

Python中一个经典的参数错误

时间:2018-06-30 15:55:26      阅读:220      评论:0      收藏:0      [点我收藏+]
 1 class Company:
 2     def __init__(self, name, staffs=[]):#实体化对象时没有传入列表,导致实体对象共用同一默认列表对象
 3         self.name = name
 4         self.staffs = staffs
 5 
 6     def add(self, staff_name):
 7         self.staffs.append(staff_name)
 8 
 9     def remove(self, staff_name):
10         self.staffs.remove(staff_name)
11 
12 if __name__=="__main__":
13     com1 = Company("com1", ["test1", "test2"])
14     com1.add("test3")
15     com1.remove("test1")
16     print("com1值:",com1.staffs)
17 
18     #com2与com3没有传入列表对象,使用了默认值作为列表对象
19     com2 = Company("com2")
20     com2.add("test2")
21     print("com2值:",com2.staffs)
22 
23     com3 = Company("com3")
24     com3.add("test3")
25     print("com2值:",com2.staffs)
26     print("com3值:",com3.staffs)
27 
28     #打印类默认值
29     print("类默认值:",Company.__init__.__defaults__)
30     #判断是否为同一对象
31     print("com2值与com3值是否为同一对象:",com2.staffs is com3.staffs)

 

输出:

 

com1值: [test2, test3]
com2值: [test2]
com2值: [test2, test3]
com3值: [test2, test3]
类默认值: ([test2, test3],)
com2值与com3值是否为同一对象: True

 

Python中一个经典的参数错误

原文:https://www.cnblogs.com/Phantom3389/p/9247331.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!