0

Ola, estou escrevendo o código para um projeto da universidade, porem quando tento importar dependencias para alguns ficheiros, da Error.

Eu criei alguns package's que possuem arquivos que têm dependências, porém elas não acham esses arquivos.

O projeto está inteiro no github, na mesma estrutura da minha máquina, para poder ajudar em um eventual solução.

Repositorio do codigo: ( GITHUB )

Estrutura dos arquivos:

inserir a descrição da imagem aqui

Inicio rodando o run.py

from agents.agent_defender import Defender

d = Defender()

Porem aparece o seguinte Error.

Traceback (most recent call last):
  File "/home/davi/PycharmProjects/AAMAS/run.py", line 1, in <module>
    from agents.agent_defender import Defender
  File "/home/davi/PycharmProjects/AAMAS/agents/agent_defender.py", line 1, in <module>
    from agents.agent import Agent
  File "/home/davi/PycharmProjects/AAMAS/agents/agent.py", line 1, in <module>
    from .states.state import State
  File "/home/davi/PycharmProjects/AAMAS/agents/states/state.py", line 2, in <module>
    from agents.agent import Agent
ImportError: cannot import name 'Agent'

File -> agent.py (agent_defender is the same thing)

from .states.state import State

"""
Is basic reference of agent.
"""


class Agent(object):

    state = None
    mail = None  # We use mail, to easily synchronize the agents per turn.
    neighbors = None  # The another agent's of this agent can communicate.

    def __init__(self):
        # check integrity of agent, when is crate

        raise NotImplementedError("subclasses must override __init__ method!\nYou can't instantiate this class!\n")

    def __change_state(self, state):
        # Responsible to change the agent state.

        raise NotImplementedError("subclasses must override change_state method!\n")

    def __valid_state(self):
        # check integrity of agent state, when is crate

        if not self.state:
            raise TypeError("The agent had have a valid state!\n")

        if isinstance(self.state, State):
            raise TypeError("The state of this agent not is instance of ' State class '!\n")

    def __str__(self):
        # Return a basic str info about the agent.

        return self.state.get_string_info()

    def get_info(self):

        return self.state.get_info()

    def recive_msg(self, data):
        # Recive msg, and do what's necessary, whit the data input and put things on mail.

        raise NotImplementedError("subclasses must override recive_msg method!\n")

    def send_msg(self, agent):
        # Send msg, whit data to another agent.

        raise NotImplementedError("subclasses must override send_msg method!\n")

    def do(self):
        # Is the principal method of the agent, because, the interpret the agent variables, and :
        # decide the state, what msg send's, read mail, made actions.
        # The method 'do', pass to state him self, and the state, using the parameters of the agent chose the action.
        # Ex.: self.state.do(self)

        self.state.do(self)

File -> state.py

from interface.model import model
from agents.agent import Agent


class State(object):
    letter = None
    Meaning = None

    def __init__(self):
        raise NotImplementedError("subclasses must override __init__ method!\nYou can't instantiate this class!\n")

    def get_info(self):
        # return info about the state to use on terminal package.

        raise NotImplementedError("subclasses must override get_info method!\n")

    def get_string_info(self):
        # This method implement's the output of the agent state.
        # Using the method model to had a eas pattern of string, receive '1 char' to represent the state

        raise NotImplementedError("subclasses must override string_info method!\n")

    def legend(self):
        # This method return (letter, meaning), info about what letter and your about meaning this state.
        # letter and meaning is string.
        # And if the letter is not be unique, the will raise a Error.

        raise NotImplementedError("subclasses must override legend method!\n")

    def do(self, agent: Agent):
        # this method, receive an agent, interpreter his values and made all necessaries actions.

        raise NotImplementedError("subclasses must override legend method!\n")

Se alguma boa alma, puder me mostrar meu erro, serei muito grato.

1 Resposta 1

1

Observei no repositório que o arquivo __init__.py dentro de "events" está vazio. É ele quem coordena o carregamento dos módulos dentro do diretório. No teu caso ele deveria ser algo como:

from states.state import State

Daí em agente.py você poderia utilizar:

import states
a = states.State( ... )

Ou então, importando a classe dentro do próprio escopo do programa:

from states import State
a = State( ... )

A documentação do Python tem um capítulo específico sobre a definição de módulos.

Este é um dos problemas, o outro é com relação ao modo como os módulos estão organizados e sendo chamados. Por exemplo, a classe "States" precisa enxergar "Agent" mas não necessariamente precisará ficar dentro desta como um submódulo. Logo, ela pode ficar na mesma hierarquia.

.
├── agents
│   ├── __init__.py
│   └── agent.py
├── interface
│   ├── __init__.py
│   └── model.py
├── states
│   ├── __init__.py
│   └── state.py
└── run.py

E as chamadas eu concentrei diretamente em "run.py":

from agents import Agent, Defender
from interface import Model
from states import State

agent = Defender()
state = State()

print(state.do(agent))

Coloquei as classe "Agent" e "Defender" no mesmo arquivo agents.py (não há necessidade em fazer um arquivo por classe).

class Agent(object):

    def __init__(self):
        self.status = 'agent'

    def __str__(self):
       return "{}".format(self.status)

class Defender(Agent):

    def __init__(self):
        self.status = 'defender'

E o arquivo __init__.py daqui faz a carga de ambas as classes:

from agents.agent import Agent, Defender

Os demais módulos são idênticos ao que mostrei acima.

Ah, e lembrando que a carga dos módulos ocorre apenas dentro de run.py.

5
  • 1
    Acrescentando fora da resposta, faz um tempo escrevi no meu blog algo bem básico sobre a construção de módulos em Python que talvez possa ajudar. 5/05/2018 às 12:56
  • Já irei testar, e dou um feed back.
    – Davi Mello
    5/05/2018 às 18:09
  • Testei não funcionou.
    – Davi Mello
    5/05/2018 às 21:35
  • Complementei com mais algumas informações, se quiser o esqueleto de código que montei é só avisar. 5/05/2018 às 23:58
  • Vou implementar, e dou o feedback. Muito obrigado pela atenção.
    – Davi Mello
    6/05/2018 às 11:00

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .