Python: public methods that call them "sister" private methods

I've only been writing Python code for a couple of weeks, so I'm still getting my head around the ground. But let's say that I have a method that MAY be called by the "user" and also be used by HEAVILY internally (ie the arguments have already been checked before being called). Here's what I'm doing now:

#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?

Floor

+2


source to share


4 answers


It's fine. However, the call to the "brother" method is incorrect in your code. 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 "via" self-assessment, since it is a method of the object, not a global function.

+2


source


There is no "true" support for private members in python, but the pythonic way to specify a member as private is to use the two leading underscores. In your case __do_something

.



See python.org for details - classes

0


source


well, unless the error checking code is very expensive, I only have one method that always checks for the error. It can repeat some of the checks, but it offers you more security, and it can come in handy if someone is inheriting from your class.

If you need performance later, you can always cache the results or do something else.

0


source


I'm just learning python myself (and enjoying it), but I think this is the way to do it. However, the private method must have two underscores and is called "self .__ do_something ()".

-1


source







All Articles