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 of f
, 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.
The first is fine; f
is redefined every time you call __init__
, but as it is local to __init__
, it has access to the entire local scope of __init__
, including the name self
.
Whether __init__
should be starting a new thread is another matter.