Is there some way I can refer to the current class object from within itself before it’s definition is completed? I have found a number of times where it would be very useful to be able to reference the currently running code object, something like ‘self’ but obviously not that. See code below which fails because ‘myClass’ is not defined at the time it is referenced:
No, the class does not yet exists. You will need to solve your underlying problem in a different way. What does exists is the local namespace, of which a writable view can be accessed with locals()
That’s the problem here. I want to encapsulate everything inside the class definition as that is just good object oriented practice but Python doesn’t seem to allow this.
I am quite curious where you’ve learned this practice - it does not align at all with what I’ve been taught about encapsulation, but I also didn’t have the greatest education so perhaps I’m just unfamiliar with this particular practice. To mii, running code with these sorts of side effects inside a class definition seems well outside of the paradigm haha
Consider the following where I would like the timer to start when the class is imported rather than each time it is instantiated. However this won’t work because at the time of it’s definition there is no ‘self’:
class MyAsyncTimer:
count: int = 0
def CleanupRoutine(self):
print("In CleanupRoutine")
while True:
print("count=", self.count)
self.count += 1
time.sleep(1)
t = threading.Thread(target=CleanupRoutine, daemon=True)
t.start()
If you want to visit the external class itself in the class code straightly, it is impossible because that in this time, the class is not created. You need to use a function and visit it in the function. Of course, it is better to add staticmethod. If you use cls as the parameter in classmethod, it may be the subclass.
@warden Your code example has raised a, new to me, piece of information and that is that init runs not just when an instance is created but also when the first class method is run.
@warden making start an @classmethod doesn’t make any difference, it still runs init which I find difficult to understand as it is not creating an instance of the class, merely running a class method.
is the part the instantiates a class. It doesn’t matter if you call an instance method or a classmethod on this instance afterwards: _init_ has already run. You can check by not calling start at all.
Is there any logical reason why a class is not available to the code within itself at load time or is this just a side-effect of the way Python is currently implemented? Could Python be changed so that it is available?
In the code below you can see that ‘myClass’ is listed in locals() but for some reason just cannot be accessed at this time.