繁体   English   中英

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

[英]Python: Public methods calling their 'brother' private methods

我只写了几周的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中没有对私有成员的“真正”支持,但是将成员表示为私有的pythonic方法是使用两个前划线。 就您而言, __do_something

有关更多详细信息,请参见python.org-classes

好吧,除非错误检查代码非常昂贵,否则我将只有一种方法,该方法始终进行错误检查。 它可能会重复进行一些检查,但确实为您提供了更高的安全性,如果有人从您的班级继承过来的话,它可能会派上用场。

如果以后需要性能,则可以随时缓存结果或执行其他操作。

我只是在自己学习python(并很喜欢它),但是我认为那是这样做的方法。 但是,私有方法应该有两个下划线,并且像“ self .__ do_something()”那样调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM