使用Python 的答案:如何从“框架”对象中检索类信息?
我得到这样的东西......
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()
这给了我以下输出:
Hello
dude
<class '__main__.A'>
显然,这会返回对类本身的引用。如果您想要类的名称,可以从__name__
属性中获取。
不幸的是,这不适用于类或静态方法......