Home > Software design >  What is the type of function inside a class by default if no args are passed?
What is the type of function inside a class by default if no args are passed?

Time:09-17

class A:
    @classmethod
    def a(x):
        print('a')

    @staticmethod
    def b():
        print('b')

    def c():
        print('c')

    def d(self): #instance method
        print(self)

A.a() # calling using class

A.b() # calling using class
A().b() # calling using instance

A.c() # calling using class

A().d() # calling using the object

A().c() # calling using instance but returning error

I've created a simple class and different methods, what is the type of method c( ) here? it is not static as if it was static method it could have been called by an instance too but it returns an error in that case, it is not an class method either as if it was, we should have get argument like cls while defining the function, so what type is the method c( ) here?

CodePudding user response:

You need @staticmethod in Python 3 if you want to call the method on an instance too. If you don't use the decorator, the method will always be passed the instance as the first parameter, causing a TypeError.

Here is an example:

>>> class A:
>>>     def f():
>>>         print('hello')

>>> A.f()
hello
>>> A().f()
TypeError: f() takes 0 positional arguments but 1 was given
>>> class A:
>>>     @staticmethod
>>>     def f():
>>>         print('hello')

>>> A.f()
hello
>>> A().f()
hello

In Python 3 there is no difference between a function defined inside a class or a function defined outside a class. Both of them are normal functions.

The self parameter (or maybe cls) comes into picture only when you access the function through an instance. Hence you don't get any error if you don't use an instance.

  • Related