如何访问属性跨class和跨Python中的文件?

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

现在我需要一个 属性,在另一个 class 中做一些事情 class。

就像:

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() 

通知:

class B的zone_id不是None时,class B可以做下一步。这意味着,如果 class A zone_id 是 None,class B 将等待它。

class Aclass B只能初始化一个实例

不同文件中的 class Aclass B

在创建初始化实例之前,您无法访问该变量。否则,w_id 不存在于 A.

如果你想给w_id一个任意值供其他classes访问,把它作为一个class变量,就是直接写在w_id = 'some value'里面class Adef 相同的缩进:

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

否则,你需要一个A的实例,像这样:

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

唯一的其他选择是在 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') 
        ...

正如您提到的,io_loop 在所有 class 中都是同一个实例,如果您的函数使用它,您可能需要创建它的副本。您不能更改变量并期望它保持不变。