一个关于对象引用容易错误的代码

 

最好不要用 列表 作为参数,否则容易得到非预期的结果,如下代码。

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")
    print ("默认参数值为: ", Company.__init__.__defaults__)
    com2.add("bobby")
    print(com2.staffs)

   
    com3 = Company("com3")
    print ("默认参数值为: ", Company.__init__.__defaults__)
    com3.add("bobby5")
    print (com2.staffs)
    print (com3.staffs)
    print (com2.staffs is com3.staffs)

输出结果如下

['bobby2', 'bobby3']
默认参数值为: ([],)
['bobby']
默认参数值为 (['bobby'],) [
'bobby', 'bobby5'] ['bobby', 'bobby5'] True
说明:
1)我们发现最后执行完后,com2.staffs和com3.staffs居然是同一个对象。
2)原因是我们在声明com2和com3时都没有指明参数staffs,他们都会使用默认的参数staffs=[],变量staffs指向了相同的内存空间。
      此时python内部就会把com2.staffs和com3.staffs当成同一个对象来处理.
3)我们可以使用Company.__init__.__defaults__查看默认的参数值是什么
 
 
posted @ 2021-04-02 17:10  坚强的小蚂蚁  阅读(63)  评论(0)    收藏  举报