__init__ Is Not Called
in the below code I am learning the difference between new and init. when I run the code I receive the following error: error: cls: Traceba
Solution 1:
The __repr__
in threding.Thread
checks whether the object has been initialized or not. This is being called when you are doing print(instance)
inside onCreateObject
. That check is required by the __repr__
implementation to function correctly (without throwing an AttributeError
).
If you overwrite the __repr__
from threading.Thread
then your example will work
classThreadWithSync(threading.Thread):
...
def__repr__(self):
return"hey"
This results in the output:
cls: <class'__main__.ThreadsWithSync'>
hey
Edited to add full example:
import threading
classThreadsWithSync(threading.Thread):
def__new__(cls):
"""
For object creation
"""print("cls: %s" % (cls))
cls.onCreateObject()
@classmethoddefonCreateObject(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()
defonInitializeObject(self):
"""
This will be invoked once the initialization procedure of the object begins.
"""print("self: %s" % (self))
def__repr__(self):
returnid(self)
ThreadsWithSync()
Solution 2:
What is written in this error message that you are trying to print object using print(instance) that is using build in repr method, but this object is not initialized yet as it is called before init.
Post a Comment for "__init__ Is Not Called"