__未调用init_uu

2024-10-03 15:24:18 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,我学习了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()

Tags: instanceinpyselfnewinitdefline
2条回答

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()

此错误消息中写入的内容是,您正试图使用使用内置repr方法的print(实例)打印对象,但此对象尚未初始化,因为它在init之前被调用

相关问题 更多 >