find class where method was defined ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Simon Burton

    #1

    find class where method was defined ?

    >>>
    >>class A(object):
    .... def foo(self): pass
    ....
    >>>
    >>class B(A):
    .... pass
    ....
    >>>
    >>b=B()
    >>b.foo
    <bound method B.foo of <__main__.B object at 0xb7b1924c>>

    How can I work out what class b.foo was defined in ?


    Simon.

  • James Stroud

    #2
    Re: find class where method was defined ?

    Simon Burton wrote:
    >>>>class A(object):
    >
    ... def foo(self): pass
    ...
    >
    >>>>class B(A):
    >
    ... pass
    ...
    >
    >>>>b=B()
    >>>>b.foo
    >
    <bound method B.foo of <__main__.B object at 0xb7b1924c>>
    >
    How can I work out what class b.foo was defined in ?
    >
    >
    Simon.
    >
    b.__class__

    --
    James Stroud
    UCLA-DOE Institute for Genomics and Proteomics
    Box 951570
    Los Angeles, CA 90095


    Comment

    • Simon Burton

      #3
      Re: find class where method was defined ?


      def methclass(meth) :
      cls = meth.im_class
      name = meth.im_func.__ name__
      meth = getattr(cls,nam e,None)
      for cls in cls.mro():
      _meth = getattr(cls,nam e,None)
      if _meth is not None and _meth==meth:
      result = cls
      return result

      >>methclass(b.f oo)
      <class '__main__.A'>


      (Turns out equality bypasses the methodwraper trickery.)

      Simon.

      Comment

      Working...