gpt4 book ai didi

Python:公共(public)方法调用它们的 'brother' 私有(private)方法

转载 作者:太空宇宙 更新时间:2023-11-04 06:31:41 24 4
gpt4 key购买 nike

我编写 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)

也就是说,您应该“通过”自引用来调用它,因为它是一个对象方法而不是全局函数。

关于Python:公共(public)方法调用它们的 'brother' 私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1631855/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com