0

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
peeyush singh
  • 1,337
  • 1
  • 12
  • 23
  • The `company` defined outside `init` is indeed a class variable. However, Python lets you access it using both `self.company` and `Emp.company`. When you defined an instance variable with the same name, it stopped mirroring the `Emp.company` value. For the sake of sanity though, it would be better not to have class and instance variables with the same name, since it leads to confusion. – shriakhilc May 31 '19 at 06:04
  • [This answer](https://stackoverflow.com/a/45121800/6698642) explains the flow better. – shriakhilc May 31 '19 at 06:09

0 Answers0