2016-09-18 81 views
1

现在我需要一个属于另一个班级在一个班级中做某事的属性。如何在Python中访问属性交叉类和交叉文件?

只是想:

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是不是无,class B下一个可以做。这意味着,如果class A zone_id是None,则class B将等待它。

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

class Aclass B在不同的文件中。

+0

B类可以保存对A类的引用吗? – shuttle87

+1

这是代码味道,但你可以简单地将'w_id'作为类变量来处理,所以'A.w_id'无处不在。 –

+0

@ shuttle87,但'A类'本身需要初始化。并且只有一个实例 – agnewee

回答

0

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

如果你想给w_id从其他类访问的任意值,把它作为一个类变量,意味着你直接w_id = 'some value'写内部A类具有相同缩进的def S:

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是在所有类别中的同一个实例,它可能会发生,你需要创建一个副本,如果你的函数使用它。你不能改变一个变量,并期望它保持不变。

+0

对不起,我无法在'B'中声明'A'实例... – agnewee

+0

@agnewee如果启动b.py并导入a.py,那么之前不会创建A的实例,因为'__name __ ='__ main __''只会在b.py中触发** **。 a.py仅作为库导入。 – Uriel

+0

事实上,'A'和'B'使用相同的'ioloop'实例,所以在上下文中,它们已经存在实例... – agnewee