【发布时间】:2020-06-11 10:06:21
【问题描述】:
我有这个简单的脚本,但在第 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 = 0和方法def number_of_people(cls):。您是否尝试在这里使用属性? -
方法和变量都只是一个类的属性。因此,这意味着类属性名称必须是唯一的,即您不能拥有同名的方法和变量
标签: python-3.x