I can’t understand how works the code below:
class Host:
name = None
fileList = []
def __init__(self, hostName):
self.name = hostName
def AddInfo(self,file):
self.fileList.append(file)
def Cleanup(self):
self.fileList = []
I create 2 instances:
h1 = Host("hostName1")
h1.AddInfo("h1")
h1.Cleanup()
print h1.fileList, Host.fileList
h2 = Host("hostName2")
h2.AddInfo("h2")
print h2.fileList, Host.fileList
the result is:
h1.fileList = [], Host.fileList = ['h1']
h2.fileList = ['h1', 'h2'], Host.fileList = ['h1', 'h2']
why Host.fileList value is changed – I assigned new values to the instance only? why h2.fileList has such value – I was expecting ['h2'] here?
This is probably easist to see by stepping through your code:
Inside your methods, when using
self.filelist, python looks to see if the instance has afilelistattribute first. If the instance doesn’t have that attribute, python looks for the attribute on the class the instance belongs to. when you doself.filelist=[]inCleanup, you are giving the instance the attributefilelist.