我对如何初始化继承的类属性感到困惑。我得到一个AttributeError
关于我认为定义良好的子属性。
我注意到在定义之后将super
调用的顺序交换到父级不会产生错误,但我不明白为什么。
我没有能够在不使用进程的情况下重现该错误(我也可以发布该测试代码,但我认为这已经足够长了),似乎超级调用的顺序并不重要。
编辑:这可能是因为在计数器被定义为yiels异常之前运行了一个进程,但如果我使用Thread
而不是{{1}则问题不会发生}。
我可能会遗漏一些关于初始化程序如何工作或做错的事情。
我正在使用以下代码。
感谢您的帮助。
以下是重现该问题的代码。我尽力使它独立。
Process
以下是我收到的消息:
from multiprocessing import Process
from multiprocessing import Queue
class Parent(object):
def __init__(self):
self._stuff_queue = Queue()
self._process = Process(target=self._do_something)
self._process.start()
def _do_something(self):
while True:
stuff = self._stuff_queue.get()
if stuff is not None:
self.something(stuff)
else:
break
def feed(self, stuff):
self._stuff_queue.put(stuff)
def something(self):
raise NotImplementedError("Implement this something !")
class Child(Parent):
def __init__(self):
# --- Swapping those two lines avoids getting the AttributeError --- #
super(Child, self).__init__() # Same thing using Parent.__init__(self)
self.counter = 0
def something(self, stuff):
self.counter += 1
print "Got stuff"
c = Child()
c.feed("Hi SO!")
c.feed(None) # Just to stop