擅长:python、mysql、java
<p>使用来自<a href="https://stackoverflow.com/questions/2203424/python-how-to-retrieve-class-information-from-a-frame-object">Python: How to retrieve class information from a 'frame' object?</a>的答案</p>
<p>我得到这样的东西。。。</p>
<pre><code>import inspect
def get_class_from_frame(fr):
args, _, _, value_dict = inspect.getargvalues(fr)
# we check the first parameter for the frame function is
# named 'self'
if len(args) and args[0] == 'self':
# in that case, 'self' will be referenced in value_dict
instance = value_dict.get('self', None)
if instance:
# return its class
return getattr(instance, '__class__', None)
# return None otherwise
return None
class A(object):
def Apple(self):
print "Hello"
b=B()
b.Bad()
class B(object):
def Bad(self):
print"dude"
frame = inspect.stack()[1][0]
print get_class_from_frame(frame)
a=A()
a.Apple()
</code></pre>
<p>它提供了以下输出:</p>
<pre><code>Hello
dude
<class '__main__.A'>
</code></pre>
<p>显然,这会返回对类本身的引用。如果需要类的名称,可以从<code>__name__</code>属性中获取。</p>
<p>不幸的是,这不适用于类或静态方法。。。</p>