1

I have this simple script but i get an operand error in Line 16

Code:

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())

Error message:

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'

What can i do to fix this error?

In this question it say i need to take the varaible name but I only want to increment and not have a variable for that

TypeError: unsupported operand type(s) for +=: 'method' and 'int' (Python)

2
  • You have a class variable number_of_people = 0 and method def number_of_people(cls): with the same name. Are you attempting to use a property here?
    – Axe319
    Jun 11, 2020 at 10:11
  • methods and variables are both just attributes of a class. as such that means that class attribute names must be unique i.e you cannot have a method and a variable with the same name Jun 11, 2020 at 10:12

1 Answer 1

0

Your static variable number_of_people and your class method def number_of_people(cls) are named the exact same thing.

Thus when you add one to cls.number_of_people, the interpreter thinks you want to add a number to the class method which doesn't make sense. You have to change the name of one of those things.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.