简体   繁体   English

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

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

I have been writing Python code for only a couple of weeks, so I'm still figuring out the lay of the land. 我只写了几周的Python代码,所以我仍然在弄清楚这片土地。 But let's say I have a method that MAY be called on by a 'user' on occasion as well as used HEAVILY internally (ie, the arguments have already been checked before the call). 但是,假设我有一个方法可以由“用户”偶尔调用,并且可以在内部大量使用(即,调用之前已经检查了参数)。 Here is what I am currently doing: 这是我目前正在做的事情:

#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

This seems logical to me. 对我来说,这似乎合乎逻辑。 Is there a better Python-ish way to do this? 有没有更好的Python方式来做到这一点?

Paul 保罗

That is fine. 那也行。 The call to the "brother" method is wrong in your code, though. 但是,在您的代码中对“兄弟”方法的调用是错误的。 You should do it like this: 您应该这样做:

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

That is, you should call it "through" the self reference, since it's an object method and not a global function. 也就是说,您应该通过自我引用来称呼它,因为它是对象方法而不是全局函数。

There is no "true" support for private members in python, but the pythonic way to indicate a member as private is to use two leading underscores. python中没有对私有成员的“真正”支持,但是将成员表示为私有的pythonic方法是使用两个前划线。 In your case, __do_something . 就您而言, __do_something

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

well, unless the error checking code is very expensive, I would have only one method, which always does the error checking. 好吧,除非错误检查代码非常昂贵,否则我将只有一种方法,该方法始终进行错误检查。 It may repeat some checks, but it does offer you more security, and it may come in handy if someone inherits from your class. 它可能会重复进行一些检查,但确实为您提供了更高的安全性,如果有人从您的班级继承过来的话,它可能会派上用场。

If later on you need performance you can always cache results or do something else. 如果以后需要性能,则可以随时缓存结果或执行其他操作。

I'm just learning python myself (and enjoying it) but I think that's the way to do it. 我只是在自己学习python(并很喜欢它),但是我认为那是这样做的方法。 However, the private method should have two underscores and called like 'self.__do_something()'. 但是,私有方法应该有两个下划线,并且像“ self .__ do_something()”那样调用。

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

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