我编写 Python 代码才几周时间,所以我仍在弄清楚这片土地的布局。但是假设我有一个方法可能会被“用户”偶尔调用并且在内部大量使用(即,参数在调用之前已经过检查)。这是我目前正在做的事情:
#The method the 'user' should call:
def do_something(self, arg1, arg2, arg3):
#write code to do error checking on arg1, agr2, arg3
#raise exceptions, return codes, etc: depends on whether you are an explicit lover
#or an implicit lover, it seems. :-)
... error checking code here...
#Now call the 'brother' method that does the real work.
return self._do_something(self, arg1, arg2, arg3, arg3)
#The method other private methods should call with already validated parameters
def _do_something(self, arg1, arg2, arg3, arg3):
#don't do error checking on the parameters. get to work...
... do what you do...
return whatever you're supposed to return
这对我来说似乎合乎逻辑。是否有更好的类似 Python 的方法来执行此操作?
保罗
请您参考如下方法:
没关系。但是,您的代码中对“兄弟”方法的调用是错误的。你应该这样做:
# Now call the 'brother' method that does the real work.
return self._do_something(arg1, arg2, arg3, arg3)
也就是说,您应该“通过”自引用来调用它,因为它是一个对象方法而不是全局函数。
