Python:公共方法调用其“兄弟”私有方法

2 投票
4 回答
1684 浏览
提问于 2025-04-15 15:25

我才刚开始写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风格的做法呢?

保罗

4 个回答

0

在Python中,并没有真正意义上的“私有”成员,但我们通常用两个下划线开头来表示一个成员是私有的。比如,你可以写成 __do_something

想了解更多,可以查看 python.org - classes

0

嗯,除非错误检查的代码特别复杂耗时,不然我会只写一个方法,这个方法总是进行错误检查。虽然可能会重复一些检查,但这样做能让你的代码更安全,而且如果有人继承你的类,这样的设计会很有用。

如果以后你需要提高性能,可以考虑缓存结果或者做其他的优化。

2

没问题。不过,你代码里调用“brother”这个方法的方式是错的。你应该这样做:

# Now call the 'brother' method that does the real work.
return self._do_something(arg1, arg2, arg3, arg3)

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

撰写回答