Search code examples
pythontornado

How to access property cross class and cross file in Python?


Now I need a property which in another class to do something in one class.

just like:

a.py

class A:
    def __init__(self, io_loop):         # the same io_loop instance 
        self.access = None
        self.w_id = None
        self.io_loop = io_loop

    @gen.coroutine
    def setup(self):
        # `async_client` has the `get`, 'post', 'put', 'delete' methods 
        self.access = yield async_client()

    @gen.coroutine
    def do_something(self):
        self.w_id = self.access.get('w_id')
        ...

    def run(self):
        self.io_loop.run_sync(self.setup)
        self.io_loop.spawn_callback(self.do_something)
        self.io_loop.start()

if __name__ == '__main__':
    a = A()
    a.run()

-

b.py

class B:
    def __init__(self, io_loop):
        self.w_id = None
        self.io_loop = io_loop           # the same io_loop instance    

    # How can i get the w_id from `class A`     

    def run(self):
        ... 

if __name__ == '__main__':
    b = B()
    b.run() 

Notice:

when zone_id of class B is not None, class B can do next. that's means, if class A zone_id is None, class B will waiting for it.

And the class A and class B only could initialize one instance.

the class A and class B in differents files.


Solution

  • You can't access that variable until you create an instance that initializes. Otherwise, w_id doesn't exist in A.

    If you want to give w_id an arbitrary value for access from other classes, put it as a class variable, means you write directly w_id = 'some value' inside class A with the same indentation as the defs:

    class A:
        w_id = something
        def __init__(self):
            ...
    class B:
        def __init__(self):
            self.w_id = A.w_id
    

    Otherwise, you need an instance of A, like that:

    class B:
        def __init__(self):
            a = A()
            a.do_something()
            self.w_id = a.w_id
    

    The only other option is to create the same functions inside B:

    class B:
        ...
        @gen.coroutine 
        def setup(self): 
            # `async_client` has the `get`, 'post', 'put', 'delete' methods
            self.access = yield async_client()   
        @gen.coroutine 
        def do_something(self): 
            self.w_id = self.access.get('w_id') 
            ...
    

    As you mentioned that io_loop is the same instance in all of the classes, it might occur that you need to create a copy of it if your functions uses it. You can't change a variable and expect it to stay unchanged.