对象在调用 inspect.getmro() 时没有属性“__bases__”

Object has no attribute '__bases__' when calling inspect.getmro()

我有一个 python class 继承自 Apache Storm MultiLang 项目的 storm.py

我的 class 如下所示:

import storm
class MyClassName(Storm.Bolt):
def initialize(self,conf,context):
     self._conf = conf;
     self._context = context
def process(self, in_tuple):
     storm.ack(in_tuple)
if __name__ == '__main__':
     MyClassName().run()

我将 python 文件 (myfilename.py) 复制到 /usr/lib64/python2.7/site-package。然后我登录 python shell 并做了一个 import myfilename。完成没有错误。当我 运行 以下 inspect.getmro(myfilename.MyClassName()) 我得到以下错误:

AttributeError: 'MyClassName' object has no attribute '__bases__' 

我的印象是当我声明我的 class 并传递它时 Storm.Bolt 我正在扩展 Storm.Bolt。我的问题是:

在 CentOs7 上使用 Python 2.7.13。风暴版本为1.1.0

inspect.getmro 函数期望它的参数是一个 class,但您传递给它的是一个实例。去掉调用 class 的括号,你的代码应该可以工作:

inspect.getmro(myfilename.MyClassName) # not MyClassName()!

如果您在问题中给出的调用是一个简化的示例,并且您在实例上调用 getmro 的地方没有直接可用的 class,您可以使用 type 得到 class:

obj = SomeClass()  # this happens somewhere earlier on, and we don't know SomeClass below

inspect.getmro(type(obj))   # but we can easily get it using type()