2

Python In a Nutshell says that:

a method defined in a class body has a mandatory first parameter, conventionally named self , that refers to the instance on which you call the method.

Does a method of a class should have at least one parameter referring to an instance?

Is it a bad practice to create a method without any parameter?

Is it a good practice to always make a method work when calling it on either the class or an instance of the class?

Note that I am not talking about a static method or class method, but an ordinary method.

>>> class C5(object):
...     def hello():
...         print('Hello')
... 
>>> C5.hello()
Hello
>>> C5().hello()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: hello() takes 0 positional arguments but 1 was given

Thanks.

  • Replace `def hello()` by `def hello(self)`. See [here](https://stackoverflow.com/a/2709832/3926995) for more informations about `self` – Chiheb Nexus Sep 06 '17 at 04:19

2 Answers2

3

You should always put self as the first parameter in the class method. If you want call class method without creating a class instance, need to write following:

class Foo:
    @staticmethod
    def hello():
        print("Hi")
amarynets
  • 1,765
  • 10
  • 27
1

Python wants you to pass self as an argument into your class methods so that python knows that the methods belong to the class that they are in.