为什么要覆盖此类的实例?

时间:2017-02-17 18:35:16

标签: python class

我正在使用FileHandler类的实例编写Python脚本,但第二个会覆盖第一个脚本,即使没有分配给相同的变量。

班级:

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

1 个答案:

答案 0 :(得分:2)

您使用__init__方法作为class方法。

对每个方法使用@classmethod都会产生一个单身,这就是变量覆盖的原因。