使用python 2.7
我正在使用装饰器创建导入对象库,导入时我会对每个对象的实例进行一些检查;主要是重复检查...
我最近转而使用super()
来利用其多重继承处理,但它在实例化的对象上引发NameError
。
class Lib(object):
def __init__(self):
print "library created"
self.lib = {}
def add_obj(self, obj):
print "object being added to library --> %s" % obj.__name__
inst = obj()
print inst.name
self.lib[obj.__name__] = obj
def Reg(obj):
global test_lib
test_lib.add_obj(obj)
test_lib = Lib()
@Reg
class A(object):
def __init__(self):
object.__init__(self)
self.name = "A instance"
@Reg
class B(object):
def __init__(self):
super(B, self).__init__()
self.name = "B instance"
>>> from testing import *
library created
object being added to library --> A
A instance
object being added to library --> B
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "testing.py", line 25, in <module>
class B(object):
File "testing.py", line 14, in Reg
test_lib.add_obj(obj)
File "testing.py", line 8, in add_obj
inst = obj()
File "testing.py", line 27, in __init__
super(B, self).__init__()
NameError: global name 'B' is not defined
似乎存在范围问题?排除装饰器,B类实例化没有问题。
有什么建议吗?
答案 0 :(得分:0)
您尝试在完成定义之前实例化B
。
从Lib.add_obj()
:
inst = obj()
print inst.name
装饰者Reg
参与了B
的定义。因此,在B
退出之前,您无法通过该名称实例化Reg
。