将方法移动到另一个 Python 文件

Move methods to another Python file

我想将我的方法(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()

Will it not cause multiple inheritance when i call them from main.py?

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

class Child(Parent):
    # ...

你所做的一切正常,你可以在任意多的 Python 文件中导入模块,只要导入依赖关系不是循环的(例如,如果 A 导入 B 导入 A).