1

I'm new to python classes and I heard that every method needs to have the "self" parameter. I didn't understand why and tried to make a method without the self parameter. I then made an instance of the class and used the method without any argument (because there's no parameters duh) and I got an error:

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

I do not understand why this happens because I haven't give any argument to the method.

Here is the code:

class hooman:
  def sayHi(self):
    print("hi")

hooman1 = hooman()
hooman1.sayHi()

It would be appreciated if someone could also tell me why is the self parameter is needed.

balderman
  • 22,927
  • 7
  • 34
  • 52
PetitJuju
  • 41
  • 3
  • 1
    Indent the def sayHi(): and print("hi"). – no ai please Aug 21 '21 at 16:40
  • code was edited and should work now – balderman Aug 21 '21 at 16:43
  • Self refers to the object (so hooman1). Basically you are doing hooman1.sayHi() but there is no self in the function header so it does not belong to hooman1. You need self to indicate that any objects you create have the properties of the class. Hope this helps. – VRComp Aug 21 '21 at 16:43
  • If you decorate the function with `@staticmethod` it will not be passed a `self` (or `cls`) parameter and you can define it with no parameters. This also allows you to call it on either an instance or on just the class itself (e.g. `hooman.sayHi()` without having to init an instance first). – Samwise Aug 21 '21 at 16:44
  • Notwithstanding previous comments, bear in mind that the word 'self' is merely a convention. As you don't have any class local variables or other functions then you could, for example, have this:- def sayHi(_) –  Aug 21 '21 at 16:45

0 Answers0