On 20/07/2012 11:07, Jose Amoreira wrote:
Hi.
This is a question about style. I have a class definition that calls a
small auxiliary function. Because this function isn't used anywhere
else, I'd like to include it inside the class definition. However, if
I do that, I'll have to use "self" in the call argument, which is (I
think) rather awkward.
Let me give an example:

def is_odd(k):
     if k % 2 == 0:
         return False
     else:
         return True

I'll point out before anyone else does that you can write this function as a one line return. I'll leave you to work out how. Personally I prefer the longer version but each to their own.


class MyOddNbr(object):
     def __init__(self, k):
         if is_odd(k):
             self.k = k
         else:
             self.k = k + 1

This works fine, but I'd like to have is_odd defined inside the class
definition, because that's the only context where that function is
used. That would be something like

class MyOddNbr(object):
     def is_odd(self,k):
         if k % 2 == 0:
             return False
         else:
             return True
     def __init__(self,k):
         if self.is_odd(k):
             self.k = k
         else:
             self.k = k + 1

This also works fine, but the function is_odd() is so simple and
generic that I find it strange to define it with is_odd(self,k) or to
call it with is_odd(self,k).
What is the pythonic way of doing this kind of stuff?

Don't put it in the class. It's a general purpose function that can be used anywhere so keep it at the module level.

Thanks.
Ze
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



--
Cheers.

Mark Lawrence.



_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to