2017-02-17 79 views
0

我正在用Python編寫一個腳本,使用FileHandler類的實例,但第二個會覆蓋第一個,即使沒有被分配到相同的變量。爲什麼這個類的實例被覆蓋?

類:

class FileHandler(): 

    name = None 
    path = None 

    @classmethod 
    def __init__(self,name,path): 
     self.name=name 
     self.path=path 

    @classmethod 
    def getName(self): 
     return self.name 

    @classmethod 
    def getPath(self): 
     return self.path 

腳本:

import fileHandler 

origen=fileHandler.FileHandler('a','b') 
destino=fileHandler.FileHandler('c','d') 

print origen.getName(),origen.getPath() 
print destino.getName(),destino.getPath() 

結果:

c d 
c d 
+4

因爲你使他們成爲了階級的方法,那麼自我真的就是階級。所有實例然後共享這些值。只是使用常規方法 – pvg

+3

@Marco您認爲'@ classmethod'的作用是什麼?您認爲什麼是類方法? – Wombatz

+0

停止使用classmethod –

回答

2

您正在使用__init__方法作爲class方法。

對每種方法使用@classmethod都會導致一個單例,這就是爲什麼變量會被覆蓋。

+0

如果我刪除'@ classmethod'似乎不分配變量。現在的輸出是:None,而不是舊值。 – Marco

+0

@MarcoAntonioAraújoMatarazzo**因爲你讓你的getters(你不應該用這個)類方法!因此,他們會得到類名稱屬性'name'和'path',你明確地設置爲'None'。只需*在代碼中刪除@classmethod的每一個出現,並在類的頂部刪除'name = None'和'path = None'。這不是你如何製作實例屬性!* –