Question

For example,

I want to return 'ClassName' from the following:

ClassName().MethodName

When I try:

ClassName().MethodName.__class__.__name__

>>instancemethod

or when I try:

ClassName().MethodName.__name__

>>MethodName

Perhaps this isn't possible, so would there be a way to turn ClassName().MethodName to ClassName(), so I could then run this, which is what I want:

ClassName().__class__.__name__
>> ClassName
Was it helpful?

Solution 2

Like so:

class Foo(object):
    def MethodName():
        pass

print type(Foo()).__name__ 
# Foo

Or,

foo=Foo()
print type(foo).__name__
# Foo

(Note -- that only works on new style classes, not legacy classes. It obviously only works if you know what to call to instantiate the class)

If all you have is reference to a method, you can use inspect (Thx Alex Martelli):

import inspect

def get_class_from_method(meth):
  for cls in inspect.getmro(meth.im_class):
    if meth.__name__ in cls.__dict__: return cls
  return None

>>> mn=Foo().MethodName
>>> get_class_from_method(mn).__name__
Foo

Or, for a user defined method, you can do:

>>> mn.im_class.__name__
Foo

OTHER TIPS

The information you want is in the im_class attribute of the bound method object:

>>> class Foo():
...   def bar():
...     pass
...
>>> m = Foo().bar
>>> m.im_class
<class __main__.Foo at 0x1073bda78>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top