How to define a function, inside a class method (for example for a threading
Thread target function), that needs access to self
?
Is the solution 1. correct or should we use 2.?
-
import threading, time class Foo: def __init__(self): def f(): while True: print(self.a) self.a += 1 time.sleep(1) self.a = 1 threading.Thread(target=f).start() self.a = 2 Foo()
It seems to work even if
self
is not a parameter off
, but is this reliable? -
import threading, time class Foo: def __init__(self): self.a = 1 threading.Thread(target=self.f).start() self.a = 2 def f(self): while True: print(self.a) self.a += 1 time.sleep(1) Foo()
This is linked to Defining class functions inside class functions: Python but not 100% covered by this question.