zoukankan      html  css  js  c++  java
  • Python中一个经典的参数错误

     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
  • 相关阅读:
    GDI+绘制字体显示不全
    vector赋值
    创建不响应(不激活)窗口
    MouseHover
    duilib窗口从任务栏恢复问题
    java 加解密
    maven依赖仲裁
    $.ajax()
    mybatis 动态SQL
    Json学习
  • 原文地址:https://www.cnblogs.com/Phantom3389/p/9247331.html
Copyright © 2011-2022 走看看