[Tutor] Where to put small auxiliary function
Jose Amoreira
ljmamoreira at gmail.com
Fri Jul 20 12:07:31 CEST 2012
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
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?
Thanks.
Ze
More information about the Tutor
mailing list