Переместить методы в другой файл Python - PullRequest
0 голосов
/ 03 июня 2018

Я хочу переместить мои методы (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()

1 Ответ

0 голосов
/ 03 июня 2018

Не приведет ли это к множественному наследованию, когда я вызываю их из main.py?

Не будет, потому что import не является наследованием.Наследование в Python выглядит следующим образом:

class Child(Parent):
    # ...

То, что вы делаете, нормально и нормально, вы можете импортировать модули в любое количество файлов Python, если хотите, чтобы зависимости импорта не были циклическими (например,было бы плохо, если бы A импортировал B, который импортирует A).

...