我想将我的方法(method_2和method_3)从main.py文件移动到其他python文件(例如method_2.py和method_3.py),然后从那里调用它们。

我有一个问题,这两个函数需要uasyncio和uasyncio.asyn模块,这也要求method_1仍位于main.py中。如果我在每个文件(method_2.py和method_3.py)中添加这些模块,当我从main.py调用它们时,是否不会引起多重继承?因为main.py已经使用了这些模块(uasyncio和uasyncio.asyn)。

main.py;

import uasyncio as asyncio
import uasyncio.asyn as asyn

loop = asyncio.get_event_loop()

async def handle_client(reader, writer):
    loop.create_task(asyn.Cancellable(method_1)())

    loop.create_task(asyn.Cancellable(method_2)())

    loop.create_task(asyn.Cancellable(method_3)())

@asyn.cancellable
async def method_1():
    print('method_1 is running')

# i want to move this function to another class or py file (for ex: method_2.py) and call it from there
@asyn.cancellable
async def method_2():
    print('method_2 is running')

# i want to move this function to another class or py file (for ex: method_3.py) and call it from there
@asyn.cancellable
async def method_3():
    print('method_3 is running')

loop.create_task(asyncio.start_server(handle_client, ipAddress, 5700))
loop.run_forever()


method_2.py;

import uasyncio as asyncio
import uasyncio.asyn as asyn

@asyn.cancellable
async def method_2():
    print('method_2 is running')


method_3.py;

import uasyncio as asyncio
import uasyncio.asyn as asyn

@asyn.cancellable
async def method_3():
    print('method_3 is running')


Revised_main.py(我已经考虑过);

import uasyncio as asyncio
import uasyncio.asyn as asyn

loop = asyncio.get_event_loop()

async def handle_client(reader, writer):
    loop.create_task(asyn.Cancellable(method_1)())

    import method_2
    loop.create_task(asyn.Cancellable(method_2.method_2)())

    import method_3
    loop.create_task(asyn.Cancellable(method_3.method_3)())

@asyn.cancellable
async def method_1():
    print('method_1 is running')

loop.create_task(asyncio.start_server(handle_client, ipAddress, 5700))
loop.run_forever()

最佳答案

当我从main.py调用它们时,它不会引起多重继承吗?


不会,因为import不是继承。 Python中的继承如下所示:

class Child(Parent):
    # ...


您所做的一切正常,可以在任意数量的Python文件中导入模块,只要导入依赖项不是循环的(例如,如果A导入B且导入)。

10-07 13:07
查看更多