确定Python类中的方法调用顺序

时间:2019-04-09 18:14:26

标签: python python-3.x python-2.7

我搜索了stackoverflow,却找不到一个好的答案。

如果我创建一个课程:

class Test():
     def foo(self):
        pass

     def bar(self):
        if bar() is called before foo(), then throw exception

有一种方法可以使某人创建一个类的实例,并在bar()之前意外地调用foo(),就像这样:

a = Test()
a.bar()

Python将引发异常,告诉用户首先调用foo()

2 个答案:

答案 0 :(得分:1)

您需要某种方法来指示在调用foo()时发生了bar() 类似以下内容可能会起作用:

class Test:
    def __init__(self):
        self.foo_called = False

    def foo(self):
        self.foo_called = True

    def bar(self):
        assert self.foo_called,"Error: foo() needs to be called first" # Or another error message

理想情况下,您的代码将为您处理此问题。如果您只需要调用一次foo(),那么它可以在__init__中,否则您可以在bar()中调用

答案 1 :(得分:1)

实例化类public void consultarRepresentantes(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String idRepresentanteString = request.getParameter("idRepresentante"); if(idRepresentanteString != null) { int idRepresentante = Integer.parseInt(idRepresentanteString); try { Representantes representante = new Representantes(idRepresentante); representante = this.rsl.buscarRepresentantePorId(representante); System.out.println(representante); byte[] foto = representante.getImage(); request.setAttribute("representante", representante); System.out.println("Codigo foto:" +foto); request.getRequestDispatcher("/consultarRepresentante.jsp").forward(request, response); } catch(Exception e) { System.out.println("Exploto el consultar"); e.printStackTrace(); } } } 的对象时只需调用foo

Test