To return the class that defined the method, the simplest way would be to just do it directly:
class A(object):
def meth(self):
return A
If meth
is defined outside the class -- and presumably attached to more than one class -- it may not be feasible to hardcode the class in the body of meth
. In that case, perhaps the easiest (only?) way for meth
to know the class on which it is defined is to store that information in meth
(as an attribute) at the time it is attached to the class.
Instead of attaching the function meth
to the class A
with
A.meth = meth
I propose using a function setmeth
which performs both A.meth = meth
and meth.thisclass = A
:
def setmeth(cls, name, meth):
setattr(cls, name, meth)
setattr(meth, 'thisclass', cls)
def meth(self):
print(meth.thisclass)
class A(object): pass
setmeth(A, 'meth', meth)
class B(A):
def meth(self):
return super(B, self).meth()
b=B()
b.meth() ##that return the class A
prints
<class '__main__.A'>