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?