is there any buitin function like ismethod, to check whether the method exists in the class.
for example,
Class sample:
def fun():
def meth()

object = sample().

passing this object(class instance) and fun(function name of class) as inputs i need to find out, whether this function is a member of class.

Thanks in advance

Recommended Answers

All 3 Replies

You can use the module inspect:

import inspect

class C1(object):
    def __init__(self):
        print "C1"
    def f1(self):
        print "f1"
    def f2(self):
        print "f2"

inst1 = C1()

    print inspect.ismethod(inst1.f1)  # True
    print inspect.ismethod(inst1.f2)  # True
    print inspect.ismethod(inst1.f3)  # 'C1' object has no attribute 'f3'
except AttributeError, error:
    print error

You can also use getattr() on class and instance objects. Examples:

>>> Plane3D
<class '__main__.Plane3D'>
>>> getattr(Plane3D, 'ThreePtCircle', None)
<unbound method Plane3D.ThreePtCircle>
>>> plane1 = Plane3D(Point(0,0,0), Point(1,0,0), Point(0,1,0))
>>> getattr(plane1, 'ThreePtCircle')
<bound method Plane3D.ThreePtCircle of Plane3D(Point(0.000000, 0.000000, 0.000000), Point(1.000000, 0.000000, 0.000000), Point(0.000000, 1.000000, 0.000000), theta=1.570796)>

You can also get it by using the class.__dict__ method.

>>> class tester(object):
	def f1(self):
		print '1'
	def f2(self):
		print '2'
	def HELLO(self):
		print 'Hello'

>>> print tester.__dict__
{'f1': <function f1 at 0x00BB8AF0>, '__module__': '__main__', 'f2': <function f2 at 0x00BB8B30>, '__doc__': None, '__dict__': <attribute '__dict__' of 'tester' objects>, '__weakref__': <attribute '__weakref__' of 'tester' objects>, 'HELLO': <function HELLO at 0x00BB8B70>}

Notice you use the __dict__ method on the class not on an instance of the class.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.