I get a type error when trying to run a code but it goes away when I just give a random argument. Can someone tell me why?

Viewed 19

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?

1 Answers

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

def add_person(h):

should be

def add_person(self , h):
Related