python对象的可变性

def add(a, b):
    a += b
    return a

if __name__ == "__main__":
    a = 1
    b = 2
    c = add(a, b)
    print(c)
    print(a, b)
    '''
    3
    1 2    
    '''

    a = [1, 2]
    b = [3, 4]
    c = add(a, b)
    print(c)
    print(a, b)
    '''
    [1, 2, 3, 4]  
    [1, 2, 3, 4] [3, 4] # 函数外的a被修改了,因为a为列表,是可变类型的
  ''' 
  a
= (1, 2)
  b
= (3, 4)
  c
= add(a, b)
  print(c)
  print(a, b)
  '''
  (1, 2, 3, 4)
  (1, 2)
(3, 4) # 函数外的a没有被修改,因为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)
    # ['bobby2', 'bobby3']

    com2 = Company("com2")
    com2.add("bobby")
    print(com2.staffs)
    # ['bobby']

    print(Company.__init__.__defaults__)
    # (['bobby'],)

    com3 = Company("com3")
    com3.add("bobby5")
    print(com2.staffs)
    print(com3.staffs)
    print(com2.staffs is com3.staffs)
    '''
    ['bobby', 'bobby5']
    ['bobby', 'bobby5']  
    True 
    '''

1.实例化对象时传入的是列表,是可变的对象
2.com2和com3实例化对象时都没有传入列表,所以它们都会使用默认的列表,即Company.__init__.__defaults__中的列表
所以com2和com3的staffs是一样的,但是com1是不一样的,因为它传入了一个列表,com1.staffs就不会指向__defaults__的值

备注:尽量不要将list/dict类型传递到函数中去,或者说传递时候一定要清楚传递进来时它是可以被修改的

猜你喜欢

转载自www.cnblogs.com/xyz2b/p/10524652.html
今日推荐