How to identify method or function in python.
Identify Method or Function in Python – Sagar Jaybhay
what is the fundamental difference between function and method?
When you write a function inside a class and it is bound to an object this is called a method. And when you write function outside a class is called function. Below code explains well.
import inspect def first(a): print(a) class Demo: def funcname(self, parameter_list): print(parameter_list) obj = Demo() print('inside of class function ismethod: ', inspect.ismethod(obj.funcname)) #True print('inside of class function isfunction: ', inspect.isfunction(obj.funcname)) #false print('outside of class function ismethod: ', inspect.ismethod(first))#false print('outside of class function isfunction: ', inspect.isfunction(first))#True
How to get the code of the function?
print(inspect.getsource(obj.funcname))
How to get a comment about function?
print(inspect.getcomments(obj.funcname))
the comment is we get first line outside the function and it is not getting inner comment and outside below function comments.
class Demo: # this is my function comment def funcname(self, parameter_list): """ this is documentation """ print(parameter_list) # this is my comments # this is outside function comment obj = Demo() print(inspect.getcomments(obj.funcname)) # output- # this is my function comment
Callables
It means any object which you called using () operator. Remember callable always return the value. Like functions and methods.
How to see the object is callable or not?
In python built-in function callable an and pass object to this.
print(callable(print)) # True Callable(10) # output- False
Different types of Callable
- Built-in function
- Built In methods
- User-defined functions
- Methods
- Classes
- Class instance – you need to explicitly call __call__ method.
What is reducing function?
These are functions that recombine an iterable recursively, ending up with a single value also called aggregators, accumulators. Ex max, min