博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python中一个经典的参数错误
阅读量:7075 次
发布时间:2019-06-28

本文共 1069 字,大约阅读时间需要 3 分钟。

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

 

转载于:https://www.cnblogs.com/Phantom3389/p/9247331.html

你可能感兴趣的文章
获取文件或是文件夹的大小和占用空间
查看>>
libssh2进行远程运行LINUX命令
查看>>
Android Gson深入分析
查看>>
Android中自动跳转到系统设置界面
查看>>
树后台数据存储(採用webmethod)
查看>>
Android利用Fiddler进行网络数据抓包【怎么跟踪微信请求】
查看>>
memcached系列之二
查看>>
树的左旋与右旋
查看>>
Atitit. 如何判断软件工程师 能力模型 程序员能力模型 项目经理能力模型...
查看>>
每周算法讲堂,二分法
查看>>
2016第8周五
查看>>
CSS3文本溢出显示省略号
查看>>
zookeeper系列之通信模型(转)
查看>>
js动态判断密码强度&&实用的 jQuery 代码片段
查看>>
Android实例-获取程序版本号(XE10+小米2)
查看>>
抛砖引玉,扒扒伪基站那些事(转)
查看>>
C#生成缩略图代码
查看>>
linux下的gedit命令使用方法与技巧
查看>>
Exception loading sessions from persistent storage
查看>>
用Eclipse替代Keil&IAR来开发ARM应用(升级版)
查看>>