Question

I have been writing Python code for only a couple of weeks, so I'm still figuring out the lay of the land. 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?

Paul

Was it helpful?

Solution

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.

OTHER TIPS

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. In your case, __do_something.

For further details, see 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. However, the private method should have two underscores and called like 'self.__do_something()'.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top