CherryPy插件设置类属性报错:'NoneType'对象无'bar'属性
CherryPy插件实例调用subscribe()后触发AttributeError的解决方法
问题场景
在CherryPy 18.8.0(Python 3.9.2、Raspian系统)中,创建多个fooPlugin插件实例时,在__init__方法里给实例设置了bar属性,但调用subscribe()后读取实例的bar属性时触发AttributeError: 'NoneType' object has no attribute 'bar'。
相关代码:
class fooPlugin(plugins.SimplePlugin): def __init__(self, bus, bar): plugins.SimplePlugin.__init__(self, bus) self.bar = bar if __name__ == '__main__': cherrypy.config.update({'server.socket_host': serverIp, #test.local', 'server.socket_port': serverPort, }) conf = { '/': { 'tools.staticdir.on': True, 'tools.staticdir.root': serverRoot, 'tools.staticdir.dir': staticDir, 'tools.staticdir.index': staticFile, } } x=fooPlugin(cherrypy.engine, 4).subscribe() y=fooPlugin(cherrypy.engine, 8).subscribe() print(x.bar)
报错信息:
File "...", line ..., in <module> print(x.bar) AttributeError: 'NoneType' object has no attribute 'bar'
问题原因
subscribe()方法的返回值是None,链式调用x=fooPlugin(...).subscribe()时,x实际被赋值为None,而非插件实例,因此无法读取bar属性。
解决方法
将实例创建与subscribe()调用拆分为两步,先创建实例并赋值给变量,再调用实例的subscribe()方法:
# 拆分创建实例和订阅操作 x = fooPlugin(cherrypy.engine, 4) x.subscribe() y = fooPlugin(cherrypy.engine, 8) y.subscribe() print(x.bar) # 正常输出4
这样x和y保存的是插件实例对象,就能正常访问bar属性了。
内容的提问来源于stack exchange,提问作者Florian
相关产品推荐
相关产品推荐

