如何解决方法和整数的操作数错误

问题描述 投票:1回答:1

我有这个简单的脚本,但在第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)

python-3.x
1个回答
0
投票

您的静态变量number_of_people和您的类方法def number_of_people(cls)被命名为完全相同的事物。

因此,当您向cls.number_of_people加一个时,解释器认为您想向类方法中添加一个没有意义的数字。您必须更改其中一项的名称。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.