__init__ 未被调用

__init__ is not called

在下面的代码中,我了解了 newinit 之间的区别。 当我 运行 代码时,我收到以下错误:

错误:

cls: <class '__main__.ThreadsWithSync'>
Traceback (most recent call last):
File "m:\python lessons\ThreadsWithSync.py", line 37, in <module>
    ThreadsWithSync()
File "m:\python lessons\ThreadsWithSync.py", line 12, in __new__
    cls.onCreateObject()
File "m:\python lessons\ThreadsWithSync.py", line 20, in onCreateObject
    print(instance)
File "C:\Users\Amr.Bakri\AppData\Local\Programs\Python\Python39\lib\threading.py", line 842, in __repr__
assert self._initialized, "Thread.__init__() was not called"
AssertionError: Thread.__init__() was not called

代码:

import threading
import logging
import time

class ThreadsWithSync(threading.Thread):

def __new__(cls):
    """
    For object creation
    """
    print("cls: %s"%(cls))
    cls.onCreateObject()
    
@classmethod
def onCreateObject(cls):
    """
    This will be invoked once the creation procedure of the object begins.
    """
    instance = super(ThreadsWithSync, cls).__new__(cls)
    print(instance)
    return instance

def __init__(self):
    """
    For object initialization
    """
    threading.Thread.__init__(self)
    print("self: %s"%(self))
    self.onInitializeObject()

def onInitializeObject(self):
    """
    This will be invoked once the initialization procedure of the object begins.
    """
    print("self: %s"%(self))
    
ThreadsWithSync()

此错误消息中写的是您正在尝试使用在 repr 方法中构建的 print(instance) 打印对象,但此对象尚未初始化为它在 init.

之前调用

threding.Thread中的__repr__检查对象是否已经初始化。当您在 onCreateObject 中执行 print(instance) 时将调用此函数。 __repr__ 实现需要该检查才能正常运行(不抛出 AttributeError)。

如果您覆盖 threading.Thread 中的 __repr__,那么您的示例将起作用

class ThreadWithSync(threading.Thread):
    ...
    def __repr__(self):
        return "hey"

这导致输出:

cls: <class '__main__.ThreadsWithSync'>
hey

编辑以添加完整示例:

import threading


class ThreadsWithSync(threading.Thread):
    def __new__(cls):
        """
        For object creation
        """
        print("cls: %s" % (cls))
        cls.onCreateObject()

    @classmethod
    def onCreateObject(cls):
        """
        This will be invoked once the creation procedure of the object begins.
        """
        instance = super(ThreadsWithSync, cls).__new__(cls)
        print(instance)
        return instance

    def __init__(self):
        """
        For object initialization
        """
        super(ThreadsWithSync, self).__init__(self)
        print("self: %s" % (self))
        self.onInitializeObject()

    def onInitializeObject(self):
        """
        This will be invoked once the initialization procedure of the object begins.
        """
        print("self: %s" % (self))

    def __repr__(self):
        return id(self)


ThreadsWithSync()