直接上代码


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("bobby4")
    print(com2.staffs)  # ['bobby4']

    com3 = Company("com3")
    com3.add("bobby5")
    print(com2.staffs)  # ['bobby4', 'bobby5']
    print(com3.staffs)  # ['bobby4', 'bobby5']
    print(com2.staffs is com3.staffs)  # True
    print(Company.__init__.__defaults__)   # (['bobby4', 'bobby5'],)

为什么com2最后和com3出来是一样的了呢?

通过print(com2.staffs is com3.staffs) # True 这一行的执行结果可以看出com2和com3的staffs指向的是同一个内存对象
也就是说Company的__init__中的staffs=[]参数,在多个对象之间是共享的。
默认参数可以通过下面方法取得:

Company.__init__.__defaults__

com2.staffs 和 com3.staffs指向的都是Company.init.__defaults__这个对象。

相关文章:

  • 2022-12-23
  • 2021-12-09
  • 2021-09-15
  • 2021-10-23
  • 2021-05-06
  • 2021-06-02
  • 2021-11-10
  • 2022-12-23
猜你喜欢
  • 2021-06-18
  • 2021-10-31
  • 2022-12-23
  • 2021-10-04
  • 2021-11-27
  • 2022-01-15
  • 2021-05-17
相关资源
相似解决方案