[ACCEPTED]-How to test if a class attribute is an instance method-instance
def hasmethod(obj, name):
return hasattr(obj, name) and type(getattr(obj, name)) == types.MethodType
0
You can use the inspect
module:
class A(object):
def method_name(self):
pass
import inspect
print inspect.ismethod(getattr(A, 'method_name')) # prints True
a = A()
print inspect.ismethod(getattr(a, 'method_name')) # prints True
0
import types
print isinstance(getattr(your_object, "your_attribute"), types.MethodType)
0
This function checks if the attribute exists 2 and then checks if the attribute is a method 1 using the inspect
module.
import inspect
def ismethod(obj, name):
if hasattr(obj, name):
if inspect.ismethod(getattr(obj, name)):
return True
return False
class Foo:
x = 0
def bar(self):
pass
foo = Foo()
print ismethod(foo, "spam")
print ismethod(foo, "x")
print ismethod(foo, "bar")
Be aware that @classmethod
-decorated functions will 14 pass all the tests in other answers. Do 13 you want these to be considered 'instance 12 methods'? Maybe it's just semantics, but 11 they by definition operate on the class, not 10 the spawned instance. I am not sure about 9 the cases where hasmethod2 (my proposed 8 solution) fails, but at least it can be 7 wary of class methods:
import inspect
import types
def hasmethod(obj, name):
return hasattr(obj, name) and type(getattr(obj, name)) == types.MethodType
def hasmethod2(obj, name):
try:
attr = getattr(obj, name)
return not inspect.isclass(attr.__self__)
except AttributeError:
return False
class Test(object):
testdata = 123
def testmethod(self):
pass
@classmethod
def testmethod2(cls):
pass
# Returns True. This may be undesired depending on your definition of 'instance method'
hasmethod(Test(), 'testmethod2')
# Returns False
hasmethod2(Test(), 'testmethod2')
It works because __self__
is 6 bound to the primary calling argument (class 5 instance for classmethod, object instance 4 for normal attributes, module or nothing 3 for various built-ins). Thus, checking for 2 the existence of __self__
and that __self__
is not a class 1 rules out non-function attributes and classmethods, respectively.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.