1


I can understand that Python requires self to be the first parameter and what not. However I'm confused by PyCharm telling me that method "hello" requires self as the first parameter when its not even being used.

As an example:

class Example:
    def hello():
       return "hello world"

This would give me an error saying "method must have a first parameter, usually called self"

Should I still be including self as a parameter even when the function/method isn't using it or should I be ignoring this error/warning? Is this because the method is inside a class?

Spoontech
  • 133
  • 13
  • 2
    Yes, you need to include the parameter because otherwise when the parameter is passed you'll get a type error. Just try `Example().hello()` and find out! If the method doesn't need `self`, though, maybe it shouldn't be an instance method? – jonrsharpe Oct 22 '19 at 09:36
  • 1
    If you try this (and you're missing parentheses after `Example`) then if you instantiate the class and try to call hello you will get a `hello() takes 0 positional arguments but 1 was given` error as it's supplying self. As @jonrsharpe says though, perhaps you need to rethink rather than just supply self. – David Buck Oct 22 '19 at 09:38

2 Answers2

6

There are multiple types of methods, the default one is an instance method and it must have a self even if not in use, but if self isn't used, it's better to define it as a static method or a class method

class Example:
    @staticmethod
    def statichello():
        return "hello world"

    @classmethod
    def classhello(cls):
        return "hello world from " + str(cls)

    def hello(self):
        return "hello world from " + str(self)

Class and static methods can be called with or without an instance:

>>> Example.statichello()
'hello world'
>>> Example().statichello()
'hello world'
>>> Example.classhello()
"hello world from <class '__main__.Example'>"
>>> Example().classhello()
"hello world from <class '__main__.Example'>"

But instance methods have to be called from an instance:

>>> Example().hello()
'hello world from <__main__.Example object at 0x000002151AF10508>'
Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62
0

'self' keyword is necessary in the method name, if you use function then no need to pass the 'self' keyword as a parameter.

class Example:
    def hello():
       return "hello world"

Here hello() is not a function, it is a method of class Example, if you are familiar with java , so in short you can say that 'self' keyword is like the 'this' keyword in java. when you called any method of class, then the object is assigned to 'self' keyword. so you can say that 'self' is used for indicate the calling object. so your code must looks like below,

class Example:
    def hello(self):
       return "hello world"
hardik gosai
  • 328
  • 3
  • 17