0

Declaring a class with method 'print' with param 'self':

class First:
  def print(self): 
    print('working') 
    return 2

Trying to call the method without instantiating the class:
First.print() getting below message:

TypeError: print() missing 1 required positional argument: 'self'

Now when instantiating the class and accessing the method: it's working.

first = First()
first.print()

# working
# 2

Now defining the same class without any param in method print:

class First:
  def print():
    print('working')
    return 2

Calling the same method without instantiating the class and it's working:

First.print()

# working
# 2

Without defining the method param, python method behaving like Static. Is it true or something else?

SuperKogito
  • 2,998
  • 3
  • 16
  • 37
  • Please correct formatting of your question (especially the source code) – Robson Apr 12 '19 at 09:20
  • In the first execution you try to call it without instantiating it, therefor there is no 'self' to pass to the method, which is why it fails. – Azer Apr 12 '19 at 09:21
  • In that examples is obviously that an static method not use self, such as your second example. You can see more examples in related question https://stackoverflow.com/questions/18679803/python-calling-method-without-self – Mihai8 Apr 12 '19 at 09:39
  • Thank you very much for the clarification.. – tellvinay2003 Apr 17 '19 at 06:16

2 Answers2

0

self refers to the bound variable or object. so it needs instantiation. where as without self method becomes static (class method in python context) and can be called using Class Name. Also you should write @classmethod decorator above the method definition. so that it is clearly state that it is a classmethod.

class First:
  @classmethod
  def print(cls):
    print('working')
    return 2
First.print()

For your reference https://medium.com/quick-code/understanding-self-in-python-a3704319e5f0

Athar
  • 963
  • 10
  • 23
  • Out of curiosity, what would be the difference between his second example, and using `@staticmethod`? – Peter Apr 12 '19 at 12:11
  • It would be pythonic way if you write @staticmethod. His 2nd exampe is basically a static method. – Athar Apr 12 '19 at 13:24
0

In the first case, it is a function of one parameter. So, Class.f() fails. In the second example, it is a function of zero parameters. So, Class.f() works.

When you create an instance, the first parameter is automatically bound to that instance, and you need to pass n-1 parameters. So, it works in your first example, but it won't work in your second.

blue_note
  • 27,712
  • 9
  • 72
  • 90