Python中一個經典的參數錯誤

來源:互聯網
上載者:User

標籤:導致   class   span   defaults   st3   div   經典   init   com   

 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

 

Python中一個經典的參數錯誤

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.