我有这个简单的脚本,但在第16行中出现操作数错误
代码:
class Person:
number_of_people = 0
Gravity = -9.5
def __init__(self, name):
self.name = name
Person.add_person()
@classmethod
def number_of_people(cls):
return cls.number_of_people
@classmethod
def add_person(cls):
cls.number_of_people += 1
p1 = Person("joe")
p2 = Person("frank")
print(Person.number_of_peple())
错误消息:
Traceback (most recent call last):
File "app4.py", line 19, in <module>
p1 = Person("joe")
File "app4.py", line 7, in __init__
Person.add_person()
File "app4.py", line 16, in add_person
cls.number_of_people += 1
TypeError: unsupported operand type(s) for +=: 'method' and 'int'
我该如何解决此错误?
在此问题中,我需要使用可变名称,但我只想增加而没有变量
TypeError: unsupported operand type(s) for +=: 'method' and 'int' (Python)
您的静态变量number_of_people
和您的类方法def number_of_people(cls)
被命名为完全相同的事物。
因此,当您向cls.number_of_people
加一个时,解释器认为您想向类方法中添加一个没有意义的数字。您必须更改其中一项的名称。