Python class attributes and their initialization -
i'm quite new in python , during these days i'm exploring classes. have question concerning attributes , variables inside classes: difference between defining attribute via q=1
in body of class , via defining self.q=1
inside __init__
? example, difference between following 2 possibilities?
class myclass1: q=1 def __init__(self,p): self.p=p def addsomething(self,x): self.q = self.q+x
and
class myclass2: def __init__(self,p): self.q=1 self.p=p def addsomething(self,x): self.q = self.q+x
the output of example:
>>> my=myclass1(2) >>> my.p 2 >>> my.q 1 >>> my.addsomething(7) >>> my.q 8
does not depend on whether myclass1
or myclass2
used. neither in myclass1
nor in myclass2
error occur.
classes instances in python uses dictionary data structure store information.
so each class definition, dictionary allocated class level information (class variables) stored. , each instance of particular class, separate dictionary(self) allocated instance specific information(instance variables) stored.
so next question is: how lookup particular name performed ??
and answer question if accessing names through instance, instance specific dictionary searched first , if name not found there, class dictionary searched name. if same value defined @ both levels former 1 overridden.
note when write d['key'] = val d dictionary, 'key' automatically added dictionary if not present. otherwise current value overwritten. keep in mind before reading further explanation.
now lets go through code have used describe problem:
myclass1
class myclass1: q=1 def __init__(self,p): self.p=p def addsomething(self,x): self.q = self.q+x
1. = myclass1(2) #create new instance , add variables it. myclass = {"q" : 1} = {"p" : 2}
2. my.p # =2, p taken dictionary of my-instance.
3. my.q # =1, q takn myclass dict. (not present in dictionary of my-instance).
4. my.addsomething(7) # method access value of q (using self.q) first # not defined in dict , hence taken # dictionary of myclass. after addition operation, # sum being stored in self.q. note # adding name q dictionary of my-instance , hence # new memory space created in dictionary of my-instance # , future references self.q fetch value # of self.q dictionary of my-instance. myclass = {"q" : 1} = {"p" : 2, "q" : 8}
5. my.q # =8, q available in dictionary of my-instance.
Comments
Post a Comment