문제

I am working with python. I want to know whether or not any method is existed or not in same module. I think getattr() does this but I couldn't do. Here is sample code saying what really I want to do with.

#python module is my_module.py
def my_func():
    # I want to check the existence of exists_method
    if getattr(my_module, exists_method):
       print "yes method "
       return
    print "No method"
def exists_method():
    pass

My main task is to dynamically call defined method. If it is not defined, just skip operations with that method and continue. I have a dictionary of data from which on the basis of keys I define some necessary methods to operate on corresponding values. for e.g. data is {"name":"my_name","address":"my_address","...":"..."}. Now I define a method called name() which I wanted to know dynamically it really exists or not.

도움이 되었습니까?

해결책

You need to look for the name as a string; and I'd use hasattr() here to test for that name:

if hasattr(my_module, 'exists_method'):
    print 'Method found!"

This works if my_module.exists_method exists, but not if you run this code inside my_module.

If exists_method is contained in the current module, you would need to use globals() to test for it:

if 'exists_method' in globals():
    print 'Method found!'

다른 팁

You can use dir,

>>> import time
>>> if '__name__' in dir(time):
...     print 'Method found'
... 
Method found
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top