'Python function call with Class name instead of object

class MyClass:
    def func1(a,b):
         print(a,b)

MyClass.func1(4,5)

I thought the above piece of code will throw error because we are accessing a method that is declared without @staticmethod decorator using class.

So does that mean the function called with class name will act like a static method ?



Solution 1:[1]

Yes, if used as a class property, there is no special mechanism instated to use it as a method:

>>> class A:
...     def f(a, b):
...         print(a,b)
...
>>> type(A.f)
<class 'function'>

However:

>>> a=A()
>>> type(a.f)
<class 'method'>
>>> a.f('only one arg because a itself is supplied as first arg')
<__main__.A object at 0x76992b70> only one arg because a itself is supplied as first arg

When a plain (no staticmethod, no classmethod) function defined inside a class is called through an instance of the class, then it is called as a method, meaning the first argument (in this case a but typically self) will be automatically provided as the instance itself.

Solution 2:[2]

You can access functions of a class from the class name itself, there is no need to create an object or use @staticmethod. MyClass is similar to str both are classes. Consider the following example:

class MyClass:
    def func1(a,b):
         print(a,b)

print(type(MyClass)) #types are the same
print(type(str)) #types are the same
x = str.__add__('test', " best") #you can use str.__add__ without using str objects
print(x) #output: test best

The output in your example works for the same reason this does. 'test' + " best" just calls __add__ just like o = MyClass() would create an object that could call func1. You are just accessing the functions that are stored in these classes and calling the function directly without assigning an object first and using the method within that object.

In this case the class is just a holder for the function. If this was the intended use you would most likely want to use a normal function rather than making in a class attribute.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tzot
Solution 2