-2

I am just starting to learn about OOP in python and came across class methods. I wrote a small bit of code to make sure I understood it properly.

class Person:
    no_of_people = 0

    def __init__(self, name):
        self.name = name
        Person.add_person()

    @classmethod
    def add_person():
        no_of_people += 1

    @classmethod
    def show_number():
        return no_of_people

When I try to run the code it shows the error message:

TypeError: add_person() takes 0 positional arguments but 1 was given

But when I just insert an argument into the class methods, the error goes away and functions just as I intended.

class Person:
    no_of_people = 0

    def __init__(self, name):
        self.name = name
        Person.add_person()

    @classmethod
    def add_person(h):
        h.no_of_people += 1

    @classmethod
    def show_number(h):
        return h.no_of_people

Can someone please explain why to me?

  • A `classmethod` receives one argument by default: the class it belongs to. If you don't want it to receive any arguments, consider using a `staticmethod` – Pranav Hosangadi Sep 07 '22 at 16:26

1 Answers1

-2

For class method you have to give self as a parameter. So

def add_person(h):

should be

def add_person(self , h):
glitch_123
  • 139
  • 12