如何决定在函数中使用返回还是纯变量操作



我知道返回就像在操作结束时抛出一个值,它实际上停止了迭代或它所在的函数。我有一段非常简单的代码,其中classmethods&使用类变量。

class Person:
number_of_people = 0
def __init__(self, name):
#Person.number_of_people +=1
Person.add_person()
@classmethod
def get_person_count(cls):
return cls.number_of_people
@classmethod
def add_person(cls):
# return cls.number_of_people+1 <-- this does not work. Output is 0 and 0. Why?
cls.number_of_people += 1 #<-- this works
P1 = Person("Rups")
print(P1.get_person_count())
P2 = Person("RG")
print(P2.get_person_count())

正如我在行中所评论的,为什么我的方法同时给出输出0,而不是预期的输出(1&2(,这是使用计划变量修改实现的?不管怎样,我认为我应该能够在init方法中使用add_person方法给出的值,因为不涉及循环。

返回值并不意味着它在修改变量。这只是意味着某些东西可以使用返回的内容。不同之处在于cls.number_of_people += 1number_of_people改变为其值+1(由于=符号(,而return cls.number_of_people+1number_of_people+1和"0";投掷";供其他人使用。

这意味着,如果add_person返回一个值,那么无论何时调用add_person((,都可以使用一个值。

# {...}
def add_person(cls):
return cls.number_of_people + 1
P1 = Person("Rups")
print(P1.add_person()) # prints 1 (number_of_people which is 0, then add 1)
print(P1.add_person()) # still prints 1

最新更新