[英]Why did my output change when I called the class attribute from an instance instead of the class?
(I'm fairly new to programming, so understand that my quary might not make sense. I've tried my best to explain it but if you are still confused, you can ask me to reclarify.) (我对编程相当陌生,所以请理解我的 quary 可能没有意义。我已尽力解释它,但如果您仍然感到困惑,您可以要求我重新澄清。)
I undertsand the that we can call the class attribute number_of_people
and increment by one so that when we create a new instance (in this context, a person), the number of people increases by one:我知道我们可以调用 class 属性number_of_people
并加一,这样当我们创建一个新实例(在此上下文中为一个人)时,人数会加一:
class Person:
# Class attribute
number_of_people = 0
# Constructor
def __init__(self, name):
self.name = name
# Everytime we call the constructor, we increment the number of people.
Person.number_of_people += 1
# Driver code
p1 = Person("Jack")
print(Person.number_of_people)
# output gives 1
However, I'm having trouble with understanding the output of the code when we change the we choose to increment p1.number_of_people instead
of Person.numer_of_people
:但是,当我们更改我们选择增加p1.number_of_people instead
Person.numer_of_people 时,我无法理解代码的Person.numer_of_people
:
class Person:
# Class attribute
number_of_people = 0
# Constructor
def __init__(self, name):
self.name = name
# Everytime we call the constructor, we increment the number of people.
p1.number_of_people += 1
# Driver code
p1 = Person("Jack")
print(p1.number_of_people)
# output gives 0 (I expected the output to be 1)
I thought that since class attributes can be accessed by both the class and instances, my change wouldn't make a difference.我认为由于 class 和实例都可以访问 class 属性,因此我的更改不会产生任何影响。 I suspect it has to do with p1
being mentioned in the class before it's mentioned in the driver code, but I'm not sure where to go from there.我怀疑它与在驱动程序代码中提到之前在 class 中提到的p1
有关,但我不确定从那里到 go 的位置。
I suspect the demonstration you were trying to do for yourself is to examine the difference between using the class attribute as a class attribute, vs as an instance attribute.我怀疑您尝试为自己做的演示是检查使用 class 属性作为 class 属性与作为实例属性之间的区别。 Consider this difference:考虑这种差异:
class Person:
population = 0
def __init__(self,name):
self.name = name
Person.population += 1
p1 = Person("Jack")
p2 = Person("Tom")
p3 = Person("Bill")
print(p1.population)
print(p2.population)
print(p3.population)
Output: Output:
3
3
3
Compared to:相比:
class Person:
population = 0
def __init__(self,name):
self.name = name
self.population += 1
p1 = Person("Jack")
p2 = Person("Tom")
p3 = Person("Bill")
print(p1.population)
print(p2.population)
print(p3.population)
Output: Output:
1
1
1
In the second example, the instance starts out using the class attribute, but as soon we change it, it creates an instance attribute that has a separate life.在第二个示例中,实例开始使用 class 属性,但一旦我们更改它,它就会创建一个具有独立生命周期的实例属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.