Trying to understand how the variable in the class are initialized. Example class:
class Emp:
company = "ABC"
I would expect the attribute company to be shared across all instance object of Emp
and we would be able to access it using Emp.company
Now if I create another variable inside the class Emp using self, and having same name (company), I expect it to be separate from the "class level" company.
The first time I try to access self.company
I expect a blank value (since nothing has been set), however the value is resolved to the same as in Emp.company
, even though later test show that these are separate values.
Example : In the init method we try to print self.company and it prints the value of Emp.company, is this giving a default value if it exists at class level something done by the run time? I suspect this has nothing to do with scoping, as I had tried to remove company from the class and have it at the module level but the script stopped compiling.
class Emp:
company = "CLASS"
def __init__ (self):
print Emp.company # prints CLASS
print self.company # prints CLASS
self.company = "SELF"
def change(self, com):
print Emp.company # prints CLASS, so that self.company = "SELF" had not effects
Emp.company = com
print Emp.company # prints CLASS2
print self.company # prints SELF, clearly the class level and self level variables are different
def show(self):
print self.company
print Emp.company
t = Emp()
t.change("CLASS2")
print "another instance"
t1 = Emp()
print "showing now....."
t1.show() # call to show that t1 has the same value as Emp.Company