In Python, how can I determine which class a method was declared in?
How can I get a reference to the class a method was declared in? In the code below, I'm trying to get a reference to Classical
in test
开发者_开发百科.
class Classical:
def method():
pass
def test(func):
# How can I get a reference to 'Classical' using only 'func'?
pass
test(Classical.method)
I've tried dir()
ing and searching, to no avail. Any ideas? (If it matters, I'm running Python 3.1)
EDIT: Changed the code to make more sense.
The function decorator test()
is executed in the context of the class Classical
while this class is being created. While executing the code in the class body, the class does not exist yet, so there is no means of accessing it. You should use a class decorator instead of a function decorator to work around this.
Alternatively, you can tell us what you are actually trying to achieve. Most probably, there will be a simple solution.
Edit: To answer your edited question: To access the class an unbound method belongs to, you can use unbound_method.im_class
in CPython 2.x. I don't know if this is portable to other Python implementations, and most probably there is a better way of achieving whatever you are trying to achieve.
精彩评论