Python类的属性和命名空间

时间:2018-05-22 08:51:41

标签: python python-3.x class scope

我有一些关于编程术语的问题。

1)我有以下代码:

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()))

此代码的输出是2,4,4,4,我认为当我们num_legs时,类变量10不会显示为print(instance.num_legs)的原因num_legs在我们尝试从类变量中读取之前,我们总是检查实例是否具有 <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div> 的属性(在这种情况下,将始终存在该属性)。

  

然而,这只是我的外行解释,我试图找出编程术语的解释。它是否与嵌套函数中的命名空间和范围类似?

0 个答案:

没有答案