擅长:python、mysql、java
<p>根据这一回应,这似乎是不可能的:</p>
<p><a href="https://stackoverflow.com/questions/7680446/get-python-functions-owning-class-from-decorator">Get Python function's owning class from decorator</a></p>
<p>相反,您可以为您的类提供一个decorator,类似于:</p>
<pre><code>class InsertMethod(object):
def __init__(self, methodToInsert):
self.methodToInsert = methodToInsert
def __call__(self, classObject):
def wrapper(*args, **kwargs):
setattr(classObject, self.methodToInsert.__name__, self.methodToInsert)
return classObject(*args, **kwargs)
return wrapper
def IWillBeInserted(self):
print "Success"
@InsertMethod(IWillBeInserted)
class Something(object):
def __init__(self):
pass
def action(self):
self.IWillBeInserted()
a = Something()
a.action()
</code></pre>