1

I have a few questions regarding programming terminologies.

1)I have the following code:

class Dog(object):
        population = 0               ## class variable--for every instance of Dog, population will be increase by 1            
        def __init__(self, name):   
            self.name = name        
            self.num_legs = 4
            Dog.population += 1     ## <== add 1 to Dog population
        def get_num_legs(self):     
            return self.num_legs

dog1 = Dog('dog1')  
dog2 = Dog('dog2')

print(Dog.population)
print(dog1.population)


## What happened?##  
dog1.num_legs = 2  #changes the instance property of dog1
print("Dog1 has {} legs".format(dog1.get_num_legs()))
print("Dog2 has {} legs".format(dog2.get_num_legs()))
Dog.num_legs = 10  #changes the class variable of Dog Class
dog1 = Dog('dog1')  ## An instance of class dog

dog2 = Dog('dog1')

print("Dog1 has {} legs".format(dog1.get_num_legs()))
print("Dog2 has {} legs".format(dog2.get_num_legs()))

The output to this code is 2,4,4,4, and I would think that the reason why the class variable num_legs will not ever be shown to be 10 when we do print(instance.num_legs) is we always check whether the instance has a property of num_legs before we try to read from the class variable(In this case there will always be that property).

However, this is just my laymen interpretation and I'm trying to find out what's the explanation with programming terminologies. Is it something similar to the namespaces and scopes in nested functions?

Prashin Jeevaganth
  • 1,223
  • 1
  • 18
  • 42
  • 1
    Please don't ask two different questions in the same question. Ask about class/instance attributes *or* nested functions, but not both. – Aran-Fey May 22 '18 at 08:56
  • @Aran-Fey I'm actually trying to figure out whether class and instances attributes can be thought of as a model similar to the scoping idea in nested functions, but either way I'm not sure of both. Is that legal? – Prashin Jeevaganth May 22 '18 at 08:59
  • A picture is worth a thousand words: https://stackoverflow.com/a/34126204/476 – deceze May 22 '18 at 09:53

0 Answers0