Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function that has access to self, inside a class method

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.?

  1. 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?

  2. 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading