Three ways to determine if a Python object can be called and its differences

Source: Internet
Author: User

Basically, there are three ways to determine whether a Python object is a callable function:

1. Using the built-in callable function

Callable (func)

Used to check if an object can be called, return TRUE or the call fails, but return false must not be called

2, determine whether the object type is Functiontype

Type (func) is functiontype# or Isinstance (func, Functiontype)

3, determine whether the object to achieve __call__ method

Hasattr (func, ' __call__ ')

Example:

# Three different ways to verify fromTypes Import FunctiontypeclassAObject): @staticmethod def F1 ():return 'From F1'@classmethod def f2 (CLS,*Arg):return 'From F2'def f3 (Self,*Arg):return 'From f3'def f4 (): Passif__name__ = ='__main__': A=A () print ('static method, instance invocation validation') Print (callable (A.F1)) # True print (Type (A.F1) isfunctiontype) # True print (hasattr (A.F1,'__call__') # True print ('static methods, class invoke validation') Print (callable (A.F2)) # True print (Type (A.F2) isfunctiontype) # False print (hasattr (A.F2,'__call__') # True print ('class Method Validation') Print (callable (A.F3)) # True print (Type (A.F3) isfunctiontype) # True print (hasattr (a.f3,'__call__') # True print ('instance Method Validation') Print (callable (A.F3)) # True print (Type (A.F3) isfunctiontype) # False print (hasattr (a.f3,'__call__') # True print ('function Validation') Print (callable (F4)) # True print (Type (F4) isfunctiontype) # True print (hasattr (F4,'__call__')) # True

"""
By running the results, it was found that the validation results of three methods were different.
The primary is the type (func) is Functiontype method, which returns false when validating class methods and instance methods,
From the debug results, the instance method, and the type of the class method are all <class ' method ', and not functiontype, so it returns false.
"""
Python is divided into functions and methods, functions are a callable object in Python (user-defined callable object, and lambda expression
The functions that are created are functions, all of which are of type functiontype, and the method is a special class function.
In the official documentation, the definition of method:
Methods is always bound to an instance of a user-defined class
Class methods and classes are bound, and instance methods are bound to instances, so both types are method.
The static method itself is not bound to the class, nor is it bound to the instance, and does not conform to the above definition, so its type should be function.

It is also important to note that if a class implements the __call__ method, its instance becomes a callable object whose type is the class that created the instance, not the function or method.
class MyClass (object):    *args, * *Kwargs)        :return  selfif ' __main__ ' :    MyClass=MyClass ()    print (callable (MyClass))    # True
So by typing to see if a Python object is callable, you need to determine whether it is a function (Functiontype) or a method (Methodtype), or whether the class implements the __call__ method.
Using the callable () method is more secure if you are simply judging whether a Python object can be called.

Three ways to determine if a Python object can be called and its differences

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.